List<T>.BinarySearch Pitfalls

The BinarySearch Method of List<T> collection can be very useful to get the zero-based index of an element.

Further more if the element you searched for is not in the List<T> you can calculate the index of the first element that is larger then the element you searched for. Just apply the ~ operator on the result of the BinarySearch:

var pos = aList.BinarySearch(aString);
if (pos < 0)
     aList.Insert(~pos, aString);

But there is one pitfall: The List<T> must already be sorted; otherwise the BinerySearch result is incorrect.
This is not a big secret. It is clearly stated in the MSDN description for the Method (under Remarks)

I saw a Bug in a Project where someone used a BinarySearch to find duplicated entries between to Lists. This works as long as the Lists are sorted. If not the result is totally nonsense.

It took a while to find this Bug.

MSDN Link:


Leave a Reply

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

You are commenting using your 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: