1

我有一个 C# 格式的 KeyValuePair 列表,格式string,int与示例内容一样:

mylist[0]=="str1",5
mylist[2]=="str1",8

我想要一些代码来删除其中一个项目,并在另一个项目中添加重复值。
所以它会是:

mylist[0]=="str1",13

定义代码:

List<KeyValuePair<string, int>> mylist = new List<KeyValuePair<string, int>>();

Thomas,我将尝试用伪代码来解释它。基本上,我想要

mylist[x]==samestring,someint
mylist[n]==samestring,otherint

变得:

mylist[m]==samestring,someint+otherint
4

4 回答 4

6
var newList = myList.GroupBy(x => x.Key)
            .Select(g => new KeyValuePair<string, int>(g.Key, g.Sum(x=>x.Value)))
            .ToList();
于 2012-12-04T07:46:12.960 回答
2
var mylist = new KeyValuePair<string,int>[2];

mylist[0]=new KeyValuePair<string,int>("str1",5);
mylist[1]=new KeyValuePair<string,int>("str1",8);
var output = mylist.GroupBy(x=>x.Key).ToDictionary(x=>x.Key, x=>x.Select(y=>y.Value).Sum());
于 2012-12-04T07:44:29.620 回答
1

我会使用不同的结构:

class Program
{
    static void Main(string[] args)
    {
        Dictionary<string, List<int>> dict = new Dictionary<string, List<int>>();
        dict.Add("test", new List<int>() { 8, 5 });
        var dict2 = dict.ToDictionary(y => y.Key, y => y.Value.Sum());
        foreach (var i in dict2)
        {
            Console.WriteLine("Key: {0}, Value: {1}", i.Key, i.Value);
        }
        Console.ReadLine();
    }
}

第一个字典应该是你的原始结构。要向其中添加元素,首先检查键是否存在,如果存在,只需将元素添加到值列表中,如果不存在,则将新项目添加到字典中。第二个字典只是第一个字典对每个条目的值列表求和的投影。

于 2012-12-04T07:48:49.870 回答
0

非 Linq 答案:

Dictionary<string, int> temp = new Dictionary<string, int>();
foreach (KeyValuePair<string, int> item in mylist)
{
    if (temp.ContainsKey(item.Key))
    {
        temp[item.Key] = temp[item.Key] + item.Value;
    }
    else
    {
        temp.Add(item.Key, item.Value);
    }
}
List<KeyValuePair<string, int>> result = new List<KeyValuePair<string, int>>(temp.Count);
foreach (string key in temp.Keys)
{
    result.Add(new KeyValuePair<string,int>(key,temp[key]);
}
于 2012-12-04T07:53:56.770 回答