Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the maximum value for each key in a List of Dictionaries using LINQ?

Tags:

c#

linq

c#-3.0

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

like image 369
Argos Avatar asked Aug 12 '09 15:08

Argos


People also ask

How do you get all the keys with the highest value in a dictionary?

To find the key with maximum value in a Python dictionary d , call max(d, key=d. get) . This returns the key with maximum value after applying the dict. get(k) method to all keys k to get their associated values.

What is the maximum size of a dictionary in C#?

The maximum capacity of a dictionary is up to 2 billion elements on a 64-bit system by setting the enabled attribute of the gcAllowVeryLargeObjects configuration element to true in the run-time environment.

Which is better list or dictionary in C#?

Dictionary is a generic type and returns an error if you try to find a key which is not there. List collection is a generic class and can store any data types to create a list. List<string> myList = new List<string>() { "Maths", "English", " Science" };

Can we use LINQ with dictionary in C #?

When we need to transform 2 columns of data table to a dictionary, we can use LINQ. Dictionary is a Key Value Pair collection and Key should be unique. You can create the Dictionary<TKey, TValue> object by passing the type of keys and values it can store.


1 Answers

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 }
like image 91
Scott Ivey Avatar answered Oct 03 '22 18:10

Scott Ivey