I\'m trying to get the key of the maximum value in the Dictionary
.
This is what I have so far:
double max
Maybe this isn't a good use for LINQ. I see 2 full scans of the dictionary using the LINQ solution (1 to get the max, then another to find the kvp to return the string.
You could do it in 1 pass with an "old fashioned" foreach:
KeyValuePair<string, double> max = new KeyValuePair<string, double>();
foreach (var kvp in results)
{
if (kvp.Value > max.Value)
max = kvp;
}
return max.Key;
You can sort dictionary by using OrderBy (for find min value) or OrderByDescending (for max value) then get first element. It also help when you need find second max/min element
Get dictionary key by max value:
double min = results.OrderByDescending(x => x.Value).First().Key;
Get dictionary key by min value:
double min = results.OrderBy(x => x.Value).First().Key;
Get dictionary key by second max value:
double min = results.OrderByDescending(x => x.Value).Skip(1).First().Key;
Get dictionary key by second min value:
double min = results.OrderBy(x => x.Value).Skip(1).First().Key;
I think using the standard LINQ Libraries this is as fast as you can go.
Little extension method:
public static KeyValuePair<K, V> GetMaxValuePair<K,V>(this Dictionary<K, V> source)
where V : IComparable
{
KeyValuePair<K, V> maxPair = source.First();
foreach (KeyValuePair<K, V> pair in source)
{
if (pair.Value.CompareTo(maxPair.Value) > 0)
maxPair = pair;
}
return maxPair;
}
Then:
int keyOfMax = myDictionary.GetMaxValuePair().Key;