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);
Comments
-
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 over 11 yearsThanks, 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 over 11 yearsI 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