在SortedDictionary中查找最接近的值

Bic*_*ick 5 c# collections dictionary sorteddictionary

我有一个SortedDictionary

 SortedDictionary<int, CPUOptimizationObject> myDict;
Run Code Online (Sandbox Code Playgroud)

现在我想找到X之上的第一个值。我可以做这样的事情

foreach (var iKey in MyDict.Keys)
{
   if (iKey >= thresholdKey)
   {
       foundKey = iKey;
       break;
   }
}
Run Code Online (Sandbox Code Playgroud)

但这不是明智的表现。
有更好的建议吗?
(集合中是否有类似Binary search for SortedDictionary之类的方法?)

Ser*_*rvy 6

虽然从理论上讲,找到大于给定值的最小项是可以在二叉搜索树上有效执行的操作(这是a SortedDictionary的实现方式),SortedDictionary但不会为您提供执行此类搜索的手段在该数据类型上。

您需要使用二进制搜索树的不同实现,以便有效地执行此类搜索,同时仍使用相同类型的数据结构。没有合适的.NET类型。您将需要使用第三方实现(其中有很多实现)。


小智 -1

我不知道这是否比 foreach 具有更好的性能,但这应该有效:

var foo = myDict.FirstOrDefault(i => i.Key > thresholdKey);
Run Code Online (Sandbox Code Playgroud)