Count values in Dictionary using LINQ and LINQ extensions

pengibot picture pengibot · Aug 14, 2012 · Viewed 21.7k times · Source

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?

Answer

Ani picture Ani · Aug 14, 2012

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