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

前端 未结 10 941
花落未央
花落未央 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 max = new KeyValuePair(); 
    foreach (var kvp in results)
    {
      if (kvp.Value > max.Value)
        max = kvp;
    }
    return max.Key;
    
    

提交回复
热议问题