Search code examples
.netsortedlist

A SortedList.IndexOfKey(key) that returns the index of the item where item.key >= key


SortedList<TKey, TValue>.IndexOfKey(key) returns -1 if key is not in the list.

Does this mean I have to implement a binary search myself if I want to find the index of the key in the list that is greater or equal to key? Or is there something out of the box that I overlooked?

I want to get the result in O(log(n)) of course, so please no LINQ iterate and filter magic.

(In general, I'd like to have something like Java's NavigableMap functionality, i.e. features like efficient iteration over a sorted map/dictionary, but for now, an answer to the above question would suffice, I can "extension-method" my way from there somehow)


Solution

  • I'm afraid you're out of luck, there's nothing built-in.

    If you create a binary search extension method for IList<T> then you could use it against the Keys property. This is a bit annoying, though not too difficult.

    (The convention used by the framework's built-in binary search methods -- Array and List<T> -- is to return the bitwise complement of the index of the next element when the element isn't found.)

    int index = yourSortedList.Keys.YourBinarySearchExtensionMethod(key);
    if (index >= 0)
    {
        // key found
    }
    else
    {
        // key not found
    }