简体   繁体   English

支持查找最接近键的C#排序字典对象?

[英]C# ordered dictionary object that supports finding closest key?

Is there any ordered dictionary collection available in C# that provides a ready means of finding the first key greater than a value if the sought value isn't present? C#中是否有任何有序的字典集合,如果不存在所寻求的值,它提供了一种寻找大于某个值的第一个键的简便方法吗?

Ie, if (!Dictionary.ContainsKey(some_key)) then return the next key > some_key based on the dictionary's ordering predicate? 即, if (!Dictionary.ContainsKey(some_key))然后根据字典的排序谓词返回下一个key > some_key

If there's a clever way of doing this with delegates an example of that would be equally appreciated! 如果有一个巧妙的方法可以与委托人一起做,那同样值得赞赏!

As Vadim suggested, your best bet would be the SortedDictionary implementation which stores the keys sorted. 正如Vadim建议的那样,最好的选择是SortedDictionary实现,该实现存储已排序的键。 From there you could do the following: 从那里,您可以执行以下操作:

var next = dictionary.ContainsKey(key)
                ? dictionary[key]
                : dictionary.FirstOrDefault(kvp => kvp.Key > key).Value;

The dictionary.FirstOrDefault will return the first key value pair where the key is greater than the desired key. dictionary.FirstOrDefault将返回键大于所需键的第一个键值对。 If there are none, then a blank key-value pair is returned {,} and the value returned should be the default value of the type stored. 如果没有,则返回一个空白的键/值对{,},并且返回的值应该是所存储类型的默认值。 Since I was playing with a SortedDictionary, it returned null. 自从我玩SortedDictionary以来,它返回了null。

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var dictionary = new SortedDictionary<int, string> {{1, "First"}, {2, "Second"}, {10, "10th"}};
            Console.WriteLine(GetNext(1, dictionary));
            Console.WriteLine(GetNext(3, dictionary));
            Console.WriteLine(GetNext(11, dictionary));

            Console.ReadLine();
        }

        private static string GetNext(int key, SortedDictionary<int, string> dictionary)
        {
            return dictionary.ContainsKey(key)
                ? dictionary[key]
                : dictionary.FirstOrDefault(kvp => kvp.Key > key).Value;
        }
    }
}

Here is a great binary-search implementation for any sorted IList : If the exact key doesn't exist, it returns the ~index of the next greatest key. 这里是任何排序的大二进制搜索实现IList :如果精确的键不存在,则返回~index的下一个最大键的。

With that class in scope one can just do something like the following: 通过将该类纳入范围,人们可以执行以下操作:

SortedList myList;
int nextBiggestKey; // Index of key >= soughtValue
if((nextBiggestKey = myList.Keys.BinarySearch(soughtValue)) < 0)
{
   if(~nextBiggestKey > myList.Count) continue; // soughtValue is larger than largest key in myList
   nextBiggestKey = ~nextBiggestKey
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM