使用C#中的List从键值对中获取总和

ani*_*ltc 0 c#

我有以下代码

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));
Run Code Online (Sandbox Code Playgroud)

现在我试图通过"Cat",我应该在变量中得到这些键的总和.如果我通过Rabbit,只传递那个数字

怎么弄这个?思考每个......

Dr.*_*ail 10

这是一个LinqWhere()和的appraochSum()

int result = list.Where(x => x.Key == "Cat").Sum(x => x.Value);
Run Code Online (Sandbox Code Playgroud)

要么

int result = list.Sum(x => x.Key == "Cat" ? x.Value : 0);
Run Code Online (Sandbox Code Playgroud)

  • @aniltc:这并不能阻止你尝试它,是吗?好奇心对于学习东西很重要. (4认同)