tags:

views:

693

answers:

1

I have a List of Dictionaries that have keys of type string and values that are ints.

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

So my question is: using LINQ how would I find the maximum value associated with each distinct key across all of the 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 would like some kind of collection that contains:

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

(I'm currently looping through the list and keeping track of things myself, really just wondering if there is a nicer LINQ-esque way of doing it)

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

+8  A: 
var results = data.SelectMany(d => d)
                  .GroupBy(d => d.Key)
                  .Select(g => new
{
    GroupName = g.Key,
    MaxValue = g.Max(i => i.Value)
});

and to test the above, use this

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

to get the following output...

{ GroupName = alpha, MaxValue = 4 }
{ GroupName = gorilla, MaxValue = 2 }
{ GroupName = gamma, MaxValue = 3 }
{ GroupName = beta, MaxValue = 3 }
{ GroupName = monkey, MaxValue = 2 }
Scott Ivey
Marvelous! Why is it always so obvious when you see it :-)
Argos
There are, of course, many other ways to do the same thing: `data.SelectMany(d => d).GroupBy(d => d.Key, d => d.Value, (k, i) => new { GroupName = k, MaxValue = i.Max() })` or `from d in data.SelectMany(i => i) group d.Value by d.Key into g select new { GroupName = g.Key, MaxValue = g.Max() }` are two of them.
Ryan Versaw