从列表中获取相同元素的总和

时间:2012-02-01 05:43:27

标签: c# c#-4.0 c#-3.0

我希望使用泛型来从列表中获得总和,如

List<Name,Value> test=new List<Name,Value>();
E.g list contain these element
test.Add(One,5);
test.Add(Second,5);
test.Add(Third,5);
test.Add(One,5);
test.Add(One,5);
test.Add(Second,5);

最终想要获得价值 具有一个名称的元素包含值15 带有第二个名称的元素包含值10 具有第三名称的元素包含值5

我不想手动迭代每个元素。 这不是一个确切的语法,它是一个想法。

2 个答案:

答案 0 :(得分:5)

你需要这样的东西吗?

            List<KeyValuePair<string, int>> test = new List<KeyValuePair<string, int>>();
test.Add(new KeyValuePair<string,int>("One",5));
test.Add(new KeyValuePair<string,int>("Second",5));
test.Add(new KeyValuePair<string,int>("Third",5));
test.Add(new KeyValuePair<string,int>("One",5));
test.Add(new KeyValuePair<string,int>("One",5));
test.Add(new KeyValuePair<string,int>("Second",5));

var result = test.GroupBy(r => r.Key).Select(r => new KeyValuePair<string, int>(r.Key, r.Sum(p => p.Value))).ToList();

答案 1 :(得分:0)

尝试:

List<KeyValuePair<string, int>> test = new List<KeyValuePair<string, int>>();
test.Add(new KeyValuePair<string,int>("One",5));
test.Add(new KeyValuePair<string,int>("Second",5));
test.Add(new KeyValuePair<string,int>("Third",5));
test.Add(new KeyValuePair<string,int>("One",5));
test.Add(new KeyValuePair<string,int>("One",5));
test.Add(new KeyValuePair<string,int>("Second",5));

var sum = test.Where( x => x.Key == "One" ).Sum( y => y.Value );