[英]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.