Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count values in Dictionary using LINQ and LINQ extensions

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?

like image 377
pengibot Avatar asked Aug 14 '12 14:08

pengibot


1 Answers

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();
like image 137
Ani Avatar answered Sep 21 '22 13:09

Ani