![](/img/trans.png)
[英]Add objects to a List nested inside a Dictionary using LINQ extensions
[英]Count values in Dictionary using LINQ and LINQ extensions
我有一个字典看起来像这样:
Dictionary<String, List<String>>
test1 : 1,3,4,5
test2 : 2,3,6,7
test3 : 2,8
如何使用LINQ和LINQ扩展计算所有值?
假设你有:
Dictionary<String, List<String>> dict = ...
如果你想要列表的数量,它就像这样简单:
int result = dict.Count;
如果您想要所有列表中所有字符串的总数:
int result = dict.Values.Sum(list => list.Count);
如果要计算所有列表中所有不同字符串的计数:
int result = dict.Values
.SelectMany(list => list)
.Distinct()
.Count();
怎么样
yourdictionary.Values.Sum(l => l.Count);
如果您想分别计算每个项目:
dict.Values.SelectMany(s => s).GroupBy(s => s)
.Select(g => new {Value = g.First(), Count = g.Count});
有了您的样本,您将获得:
“1”,1; “3”,2; “4”,1; “5”,1,“6”,1; “7”,1; “8”,1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.