Good way to get the key of the highest value of a Dictionary in C#

前端 未结 10 947
花落未央
花落未央 2020-12-04 17:33

I\'m trying to get the key of the maximum value in the Dictionary results.

This is what I have so far:

double max          


        
10条回答
  •  不思量自难忘°
    2020-12-04 18:08

    Little extension method:

    public static KeyValuePair GetMaxValuePair(this Dictionary source)
        where V : IComparable
    {
        KeyValuePair maxPair = source.First();
        foreach (KeyValuePair pair in source)
        {
            if (pair.Value.CompareTo(maxPair.Value) > 0)
                maxPair = pair;
        }
        return maxPair;
    }
    

    Then:

    int keyOfMax = myDictionary.GetMaxValuePair().Key;

提交回复
热议问题