Reputation: 2824
I want to get sum from the list using generics as like
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);
At the end want to get value as like Element with One name contain value 15 Element with Second name contain value 10 Element with Third name contain value 5
I don't want to iterate each element manually. This is not an exact syntax, it an idea.
Upvotes: 1
Views: 2074
Reputation: 25337
Try :
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 );
Upvotes: 0
Reputation: 4585
do you need something like this
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();
Upvotes: 6