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

前端 未结 10 894
花落未央
花落未央 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:01

    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;
    
    
    0 讨论(0)
  • 2020-12-04 18:02

    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;
    
    0 讨论(0)
  • 2020-12-04 18:02

    I think using the standard LINQ Libraries this is as fast as you can go.

    0 讨论(0)
  • 2020-12-04 18:08

    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;

    0 讨论(0)
提交回复
热议问题