Open Rob-Hague opened 7 months ago
It seems unlikely that we would expose a second binary search method just to make this behaviour possible. We might consider exposing it as an overload:
public int IndexOfKey(TKey key, bool encodeNearestMatchAsBitwiseComplement);
Or we could just update the existing IndexOfKey
documentation & implementation to just return what the underlying Array.BinarySearch
gives back. Changing the contract of the return value to be negative instead of specifically -1
sounds like an acceptable breaking change to me. @bartonjs @stephentoub thoughts?
.... I guarantee that people have:
public const int NOT_FOUND = -1;
somewhere....
Background and motivation
SortedList<TKey, TValue>
exposesint IndexOfKey(TKey key)
which performs a binary search on the sorted keys array and returns "The zero-based index of key within the entire SortedList<TKey,TValue>, if found; otherwise, -1."List<T>
exposesint BinarySearch(T item)
which when a value is not found, returns "a negative number that is the bitwise complement of the index of the next element that is larger than item or, if there is no larger element, the bitwise complement of Count."Often I want to find the index in my SortedList representing the highest key <= my TKey, or the smallest key >= my TKey etc. There are similar asks in #24022 and on stackoverflow
This proposal is to expose
int BinarySearch (TKey key)
which has the same return behaviour as that onList<T>
.API Proposal
API Usage
Alternative Designs
Strongly-type
SortedList<TKey, TValue>.Keys
as returningSortedList<TKey, TValue>.KeyList
and make the latter public (note: it is public in src but not in ref), then expose the method on there.Usage:
Risks
No response