繁体   English   中英

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

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

C#中是否有任何有序的字典集合,如果不存在所寻求的值,它提供了一种寻找大于某个值的第一个键的简便方法吗?

即, if (!Dictionary.ContainsKey(some_key))然后根据字典的排序谓词返回下一个key > some_key

如果有一个巧妙的方法可以与委托人一起做,那同样值得赞赏!

正如Vadim建议的那样,最好的选择是SortedDictionary实现,该实现存储已排序的键。 从那里,您可以执行以下操作:

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

dictionary.FirstOrDefault将返回键大于所需键的第一个键值对。 如果没有,则返回一个空白的键/值对{,},并且返回的值应该是所存储类型的默认值。 自从我玩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;
        }
    }
}

这里是任何排序的大二进制搜索实现IList :如果精确的键不存在,则返回~index的下一个最大键的。

通过将该类纳入范围,人们可以执行以下操作:

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