[英]Getting sum from key value pair using List in C#
I have following code 我有以下代码
var list = new List<KeyValuePair<string, int>>();
list.Add(new KeyValuePair<string, int>("Cat", 1));
list.Add(new KeyValuePair<string, int>("Cat", 2));
list.Add(new KeyValuePair<string, int>("Rabbit", 4));
Now I am trying to pass "Cat"
and I should get sum of these keys in a variable.If I pass Rabbit, pass only that number 现在,我尝试传递
"Cat"
并且应该在变量中获取这些键的总和。如果传递Rabbit,则仅传递该数字
How to get this ? 如何得到这个? thinking of for-each....
考虑每个...
Here is a Linq
appraoch with Where()
and Sum()
这是带有
Where()
和Sum()
的Linq
方法
int result = list.Where(x => x.Key == "Cat").Sum(x => x.Value);
or 要么
int result = list.Sum(x => x.Key == "Cat" ? x.Value : 0);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.