Count values in Dictionary using LINQ and LINQ extensions

心不动则不痛 提交于 2019-12-05 02:26:38
Ani

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();
Nikhil Agrawal

How about

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

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

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