получить сумму того же элемента из списка - PullRequest
1 голос
/ 01 февраля 2012

Я хочу получить сумму из списка, используя дженерики, как

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 ]

5 голосов
/ 01 февраля 2012

тебе нужно что-то вроде этого

            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();
0 голосов
/ 01 февраля 2012

Попробуйте:

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 );
...