Developing on Staxmanade

BinarySearchOrDefault()

When you need to use BinarySearch on a large List<T>, you need to declare a long to hold the return index value of the search. When the item in the list is not found the value returned from the binary search is negative and depending on it's value can mean different things. However most of the time I use this search method I don't care about these other options. Either give me the value I am searching for or give me the default value of <T>.

I wrote a little helper extension that will return the found object or if the item could not be fount it returns default(T).


public static T BinarySearchOrDefault<T>(this
List<T> list,
T item,
IComparer<T> comparer)
{
int returnIndex = list.BinarySearch(item, comparer);

if (returnIndex >= 0)
return list[returnIndex];
else
return default(T);
}