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

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

    How about doing it in parallel using Interlocked.Exchange for thread safety :) Keep in mind that Interlocked.Exchange will only work with a reference type.(i.e. a struct or key value pair (unless wrapped in a class) will not work to hold the max value.

    Here's an example from my own code:

    //Parallel O(n) solution for finding max kvp in a dictionary...
    ClassificationResult maxValue = new ClassificationResult(-1,-1,double.MinValue);
    Parallel.ForEach(pTotals, pTotal =>
    {
        if(pTotal.Value > maxValue.score)
        {
            Interlocked.Exchange(ref maxValue, new                
                ClassificationResult(mhSet.sequenceId,pTotal.Key,pTotal.Value)); 
        }
    });
    

    EDIT (Updated code to avoid possible race condition above):

    Here's a more robust pattern which also shows selecting a min value in parallel. I think this addresses the concerns mentioned in the comments below regarding a possible race condition:

    int minVal = int.MaxValue;
    Parallel.ForEach(dictionary.Values, curVal =>
    {
      int oldVal = Volatile.Read(ref minVal);
      //val can equal anything but the oldVal
      int val = ~oldVal;
    
      //Keep trying the atomic update until we are sure that either:
      //1. CompareExchange successfully changed the value.
      //2. Another thread has updated minVal with a smaller number than curVal.
      //   (in the case of #2, the update is no longer needed)
      while (oldval > curVal && oldval != val)
      {
        val = oldval;
        oldval = Interlocked.CompareExchange(ref minVal, curVal, oldval);
      }
    });
    

提交回复
热议问题