Count values in Dictionary using LINQ and LINQ extensions

安稳与你 提交于 2019-12-06 20:10:24

问题


I have a dictionary that looks something like this:

Dictionary<String, List<String>>

test1 : 1,3,4,5
test2 : 2,3,6,7
test3 : 2,8

How can I get a count of all the values using LINQ and LINQ extensions?


回答1:


Let's say you have:

Dictionary<String, List<String>> dict = ...

If you want the number of lists, it's as simple as:

int result = dict.Count;

If you want the total count of all the strings in all the lists:

int result = dict.Values.Sum(list => list.Count);

If you want the count of all the distinct strings in all the lists:

int result = dict.Values
                 .SelectMany(list => list)
                 .Distinct()
                 .Count();



回答2:


How about

yourdictionary.Values.Sum(l => l.Count);



回答3:


In case you want to count each item separately:

dict.Values.SelectMany(s => s).GroupBy(s => s)
    .Select(g => new {Value = g.First(), Count = g.Count});

With your sample you'll get:

"1", 1; "3", 2; "4", 1; "5", 1, "6", 1; "7", 1; "8", 1



来源:https://stackoverflow.com/questions/11954608/count-values-in-dictionary-using-linq-and-linq-extensions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!