Count values in Dictionary using LINQ and LINQ extensions

24,301

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

Solution 2

How about

yourdictionary.Values.Sum(l => l.Count);
Share:
24,301
pengibot
Author by

pengibot

Updated on July 09, 2022

Comments

  • pengibot
    pengibot almost 2 years

    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?

  • pengibot
    pengibot over 11 years
    Thanks, Yeah it was the total count of all the strings in all the lists I was after. Very concise and well explained answer. I am new to Linq so am still getting use to how to do things.
  • pengibot
    pengibot over 11 years
    I was also after the way to do it using from mylist in dict where logic too, which would be useful to see how to do the same. thanks