Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find key with max value from SortedDictionary?

I have a SortedDictionary how do I find the key associated with the max value? Do I have to loop through every KeyValuePair?

like image 362
User Avatar asked Jul 18 '12 20:07

User


2 Answers

If dict is your SortedDictionary<,> (or any IDictionary<,>) and you want all the keys that correspond to the max value, first check that dict is not null or empty (you need at least one element). Then maybe this works:

var max = dict.Values.Max();
var relevantKeys = dict.Where(pair => max.Equals(pair.Value))
    .Select(pair => pair.Key);

Maybe it can be done more efficiently?

like image 188
Jeppe Stig Nielsen Avatar answered Sep 23 '22 22:09

Jeppe Stig Nielsen


Use Enumerable.OrderByDescending() and then access the Key property of what First() returns like so:

 var dict = new SortedDictionary<string, string>
                       {
                           {"key1", "value3"},
                           {"key2", "value1"},
                           {"key3", "value2"},
                       };

        var max = dict.OrderByDescending(d => d.Value).First();
        var key = max.Key;
like image 22
Sumo Avatar answered Sep 24 '22 22:09

Sumo