Bick
Bick

Reputation: 18551

Finding nearest 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 isn't good performance wise.
Any better suggestion?
(is there a method for that in the collections something like Binary search for SortedDictionary ?)

Upvotes: 8

Views: 2459

Answers (4)

Peter
Peter

Reputation: 2267

create a temp list n using a .toList() on your Sorteddictionary Now since that results a List n you could do

  n.Find(item =>item >20)

to retrieve the first key in return that matches,

Upvotes: -1

Koryu
Koryu

Reputation: 1381

You could try if this is faster. But I guess it will be faster only if you are performing the search multiple times.

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

Upvotes: 0

Servy
Servy

Reputation: 203838

While, in theory, finding the smallest item that is larger than a given value is an operation that can be performed efficiently on a Binary Search Tree (which is what a SortedDictionary is implemented as) SortedDictionary does not expose the means for you to perform such a search on that data type.

You would need to use a different implementation of a Binary Search Tree in order to efficiently perform such a search, while still using the same type of data structure. There are no suitable .NET types; you would need to use a 3rd party implementation (of which there are quite a few out there).

Upvotes: 7

Alexandre Machado
Alexandre Machado

Reputation: 587

I don't know if this has better performance than the foreach, but this should work:

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

Upvotes: -1

Related Questions