How to find the maximum value for each key in a dictionary list using LINQ?

I have a list of dictionaries that have string keys and ints values.

Many dictionaries have the same keys in them, but not all.

So my question is: using LINQ, how would I find the maximum value associated with each individual key in all dictionaries?

So, for example, given the following input:

var data = new List<Dictionary<string, int>> { new Dictionary<string, int> {{"alpha", 4}, {"gorilla", 2}, {"gamma", 3}}, new Dictionary<string, int> {{"alpha", 1}, {"beta", 3}, {"gamma", 1}}, new Dictionary<string, int> {{"monkey", 2}, {"beta", 2}, {"gamma", 2}}, }; 

I need some kind of collection containing:

 {"alpha", 4}, {"gorilla", 2}, {"gamma", 3}, {"beta", 3}, {"monkey", 2} 

(I am currently browsing the list and tracking things myself, really just wondering if there is a more convenient LINQ-esque way)

EDIT: I also don't know what string keys are in advance

+6
c # linq
source share
1 answer
 var results = data.SelectMany(d => d) .GroupBy(d => d.Key) .Select(g => new { GroupName = g.Key, MaxValue = g.Max(i => i.Value) }); 

and to check it use this

 foreach (var item in results) { Console.WriteLine(item); } 

to get the following result ...

 { GroupName = alpha, MaxValue = 4 } { GroupName = gorilla, MaxValue = 2 } { GroupName = gamma, MaxValue = 3 } { GroupName = beta, MaxValue = 3 } { GroupName = monkey, MaxValue = 2 } 
+9
source share

All Articles