问题
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?
回答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();
回答2:
How about
yourdictionary.Values.Sum(l => l.Count);
回答3:
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
来源:https://stackoverflow.com/questions/11954608/count-values-in-dictionary-using-linq-and-linq-extensions