Finding the closest value in a SortedDictionary

I have a SortedDictionary

 SortedDictionary<int, CPUOptimizationObject> myDict;

Now I want to find the first value above X. I can do something like this

foreach (var iKey in MyDict.Keys)
{
   if (iKey >= thresholdKey)
   {
       foundKey = iKey;
       break;
   }
}

but this is not very good performance.
Any better suggestion?
(is there a method for collections like binary search SortedDictionary?)

+4
source share
4 answers

Although theoretically, searching for the smallest element that is greater than a given value is an operation that can be effectively performed on a binary search tree (which is implemented SortedDictionaryas), it SortedDictionarydoes not reveal the means for performing such a search in this data type.

, , . .NET; ( ).

+3

, . , , .

var keys = new List<int>(myDict.Keys);
int index = keys.BinarySearch(thresholdKey);
0

temp n .toList() Sorteddictionary , n

  n.Find(item =>item >20)

, ,

0

, , foreach, :

var foo = myDict.FirstOrDefault(i => i.Key > thresholdKey);
-2

All Articles