What’s annoying about SortedList(TKey, TValue).IndexOfKey; a.k.a., what’s sweet about Reflector

http://philosopherdeveloper.com/posts/whats-annoying-about-sorted-list-index-of-key.html

Advertisements

4 thoughts on “What’s annoying about SortedList(TKey, TValue).IndexOfKey; a.k.a., what’s sweet about Reflector

  1. Daniel, why does `BinarySearch(this IList list, T value)` have generic type constraint and other methods – not?

    • Daniel says:

      What do you mean by constraint? Do you mean why is it generic at all? I suppose the most logical reason I could give for that is simply that it makes more sense to consider a list “sorted” (and therefore eligible for a binary search) if every element is of the same type. However, I suppose you could also write a BinarySearch method to accept any IList (non-generic) and an IComparer (again, non-generic). Theoretically this way you could even run a binary search on something like an ArrayList full of different types of objects (which would be weird, but kind of cool, too). A significant downside to this approach, of course, would be the inevitable boxing of value types. Since a binary search is generally used for performance reasons, this seems like a pretty big drawback to the non-generic alternative.

  2. jack says:

    Great find, but what does this help when SortedList does not implement IList? There is little use for the closest int index when we can only read from the list with TKey which again triggers a new binary search.

    • Daniel says:

      Sorry for the delayed response. SortedList does not itself implement IList, but the SortedList.Keys and SortedList.Values properties do. So if you want to search for either a specific key or a specific value, this code will allow you do that.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: