Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use BinarySearch for List<T>

Let's start with this overload of List BinarySearch:

public int BinarySearch(T item, IComparer<T> comparer);

It is well known that the list should be sorted with the appropiate IComparer before using BinarySearch. But then: to search the list you will have to provide a T item. This is rather unexpected when one is used to searching items in the list based on properties of these items (i.e. using Linq or delegates/predicates). Because when I already have my T item I don't have to search it!

Now I was implementing C++ code in C# and saw that the C++ programmer used C++ style binary searches everywhere in his code as follows. First he made a new T item and gave this T item the properties he was looking for. Then he searched the list with it, to find the index of an item in the list with the same properties. The C++ comparer of course was adapted to these properties.

So this is a quite different way to look up items in a List. BinarySearch makes a dummy T item and searches for an index with which it can retrieve the real T item in the list. From a Linq point of view this feels unnatural.

My questions are:

Did I give a correct description of the idea behind BinarySearch?

Do you think it is possible to use a Linq style search with BinarySearch without making a dummy T item first?

like image 887
Gerard Avatar asked Feb 08 '11 08:02

Gerard


1 Answers

Did I give a correct description of the idea behind BinarySearch?
Yes.

Do you think it is possible to use a Linq style search with BinarySearch without making a dummy T item first?
Not in it's current form. You could use a wrapper that would create the dummy T for you, it would only work for specific Ts, though (with parameterless constructors, etc.).

like image 79
Jaroslav Jandek Avatar answered Oct 16 '22 21:10

Jaroslav Jandek