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

前端 未结 10 942
花落未央
花落未央 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 17:50

    After reading various suggestions, I decided to benchmark them and share the results.

    The code tested:

    // TEST 1
    
    for (int i = 0; i < 999999; i++)
    {
      KeyValuePair bestMove1 = possibleMoves.First();
      foreach (KeyValuePair move in possibleMoves)
      {
        if (move.Value > bestMove1.Value) bestMove1 = move;
      }
    }
    
    // TEST 2
    
    for (int i = 0; i < 999999; i++)
    {
      KeyValuePair bestMove2 = possibleMoves.Aggregate((a, b) => a.Value > b.Value ? a : b);
    }
    
    // TEST 3
    
    for (int i = 0; i < 999999; i++)
    {
      KeyValuePair bestMove3 = (from move in possibleMoves orderby move.Value descending select move).First();
    }
    
    // TEST 4
    
    for (int i = 0; i < 999999; i++)
    {
      KeyValuePair bestMove4 = possibleMoves.OrderByDescending(entry => entry.Value).First();
    }
    

    The results:

    Average Seconds Test 1 = 2.6
    Average Seconds Test 2 = 4.4
    Average Seconds Test 3 = 11.2
    Average Seconds Test 4 = 11.2
    

    This is just to give an idea of their relative performance.

    If your optimizing 'foreach' is fastest, but LINQ is compact and flexible.

提交回复
热议问题