First, to use this method, the list must be ordered . This is a precondition for the binary search algorithm, but it's easy to remember ...
Second, the BinarySearch
method with a single argument assumes that the list is ordered according to the criterion of "natural" comparison of its elements. That is, it is necessary for these elements to implement the interface IComparable
(or its generic variant) as long as the list is ordered according to this criterion. In the case of string lists, the comparison is given in lexicographic order.
If you need more control over the benchmark, use the variant that receives a IComparer
. Always remember that the list must be ordered under the same criteria , so that the binary search works correctly.
The method return is the position the element is in the list, if it is there, or a negative number if it is not. Note that if there is more than one occurrence of the element in the list, any of them may be returned, not necessarily the first one (depending on how many elements the list has and what positions its element occupies).
If the return is a negative number, the element is not in the list. If your goal is to just fetch, just test if the return is less than zero. But if you want to insert this element in the list if it is not already there, the return value can help you determine where this insertion should occur: just pick up the bitwise complement of the return value:
List<string> lista = new List<string>() { "aoo", "bar", "baz" };
Console.WriteLine(lista.BinarySearch("bar")); // Está na lista (posição 1)
Console.WriteLine(lista.BinarySearch("bay")); // Não na lista (negativo)
Console.WriteLine(~lista.BinarySearch("bay")); // Se for inserir, insira na posição 2
Example in ideone .