问题
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 ?)
回答1:
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).
回答2:
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);
回答3:
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,
回答4:
I don't know if this has better performance than the foreach, but this should work:
var foo = myDict.FirstOrDefault(i => i.Key > thresholdKey);
来源:https://stackoverflow.com/questions/20474896/finding-nearest-value-in-a-sorteddictionary