Finding nearest value in a SortedDictionary

c#, collections, dictionary, sorteddictionary

Solution

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).

Problem

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 ?)

Original source

Related problems