I have a SortedDictionary
how do I find the key associated with the max value? Do I have to loop through every KeyValuePair?
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?
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With