簡體   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