簡體   English   中英

使用C#中的List從鍵值對中獲取總和

[英]Getting sum from key value pair using List in 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));

現在,我嘗試傳遞"Cat"並且應該在變量中獲取這些鍵的總和。如果傳遞Rabbit,則僅傳遞該數字

如何得到這個? 考慮每個...

這是帶有Where()Sum()Linq方法

int result = list.Where(x => x.Key == "Cat").Sum(x => x.Value);

要么

int result = list.Sum(x => x.Key == "Cat" ? x.Value : 0);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM