Skip to main content
.NET Framework Class Library
ListTBinarySearch Method (T, IComparerT)

Searches the entire sorted ListT for an element using the specified comparer and returns the zero-based index of the element.

Namespace:   System.Collections.Generic
Assembly:  mscorlib (in mscorlib.dll)
Syntax
Public Function BinarySearch ( _
	item As T, _
	comparer As [%$TOPIC/ftfdbfx6_en-us_VS_110_2_0_0_0_0%](Of T) _
) As [%$TOPIC/ftfdbfx6_en-us_VS_110_2_0_0_0_1%]
public [%$TOPIC/ftfdbfx6_en-us_VS_110_2_0_1_0_0%] BinarySearch(
	T item,
	[%$TOPIC/ftfdbfx6_en-us_VS_110_2_0_1_0_1%]<T> comparer
)
public:
[%$TOPIC/ftfdbfx6_en-us_VS_110_2_0_2_0_0%] BinarySearch(
	T item, 
	[%$TOPIC/ftfdbfx6_en-us_VS_110_2_0_2_0_1%]<T>^ comparer
)
member BinarySearch : 
        item:'T * 
        comparer:[%$TOPIC/ftfdbfx6_en-us_VS_110_2_0_3_0_0%]<'T> -> [%$TOPIC/ftfdbfx6_en-us_VS_110_2_0_3_0_1%]

Parameters

item
Type: T

The object to locate. The value can be for reference types.

comparer
Type: System.Collections.GenericIComparer T

The IComparerT implementation to use when comparing elements.

-or-

to use the default comparer ComparerTDefault.

Return Value

Type: SystemInt32
The zero-based index of item in the sorted ListT, if item is found; otherwise, a negative number that is the bitwise complement of the index of the next element that is larger than item or, if there is no larger element, the bitwise complement of Count.
Exceptions
ExceptionCondition
InvalidOperationException

comparer is , and the default comparer ComparerTDefault cannot find an implementation of the IComparableT generic interface or the IComparable interface for type T.

Remarks

The comparer customizes how the elements are compared. For example, you can use a CaseInsensitiveComparer instance as the comparer to perform case-insensitive string searches.

If comparer is provided, the elements of the ListT are compared to the specified value using the specified IComparerT implementation.

If comparer is , the default comparer ComparerTDefault checks whether type T implements the IComparableT generic interface and uses that implementation, if available. If not, ComparerTDefault checks whether type T implements the IComparable interface. If type T does not implement either interface, ComparerTDefault throws InvalidOperationException.

The ListT must already be sorted according to the comparer implementation; otherwise, the result is incorrect.

Comparing with any reference type is allowed and does not generate an exception when using the IComparableT generic interface. When sorting, is considered to be less than any other object.

If the ListT contains more than one element with the same value, the method returns only one of the occurrences, and it might return any one of the occurrences, not necessarily the first one.

If the ListT does not contain the specified value, the method returns a negative integer. You can apply the bitwise complement operation (~) to this negative integer to get the index of the first element that is larger than the search value. When inserting the value into the ListT, this index should be used as the insertion point to maintain the sort order.

This method is an O(log n) operation, where n is the number of elements in the range.

Examples

The following code example demonstrates the Sort(IComparerT) method overload and the BinarySearch(T, IComparerT) method overload.

The code example defines an alternative comparer for strings named DinoCompare, which implements the IComparer<string> (IComparer(Of String) in Visual Basic, IComparer<String^> in Visual C++) generic interface. The comparer works as follows: First, the comparands are tested for , and a null reference is treated as less than a non-null. Second, the string lengths are compared, and the longer string is deemed to be greater. Third, if the lengths are equal, ordinary string comparison is used.

A ListT of strings is created and populated with four strings, in no particular order. The list is displayed, sorted using the alternate comparer, and displayed again.

The BinarySearch(T, IComparerT) method overload is then used to search for several strings that are not in the list, employing the alternate comparer. The Insert method is used to insert the strings. These two methods are located in the function named SearchAndInsert, along with code to take the bitwise complement (the ~ operator in C# and Visual C++, Xor -1 in Visual Basic) of the negative number returned by BinarySearch(T, IComparerT) and use it as an index for inserting the new string.

Imports System
Imports System.Collections.Generic

Public Class DinoComparer
    Implements IComparer(Of String)

    Public Function Compare(ByVal x As String, _
        ByVal y As String) As Integer _
        Implements IComparer(Of String).Compare

        If x Is Nothing Then 
            If y Is Nothing Then  
                ' If x is Nothing and y is Nothing, they're 
                ' equal.  
                Return 0
            Else 
                ' If x is Nothing and y is not Nothing, y 
                ' is greater.  
                Return -1
            End If 
        Else 
            ' If x is not Nothing... 
            ' 
            If y Is Nothing Then 
                ' ...and y is Nothing, x is greater. 
                Return 1
            Else 
                ' ...and y is not Nothing, compare the  
                ' lengths of the two strings. 
                ' 
                Dim retval As Integer = _
                    x.Length.CompareTo(y.Length)

                If retval <> 0 Then  
                    ' If the strings are not of equal length, 
                    ' the longer string is greater. 
                    ' 
                    Return retval
                Else 
                    ' If the strings are of equal length, 
                    ' sort them with ordinary string comparison. 
                    ' 
                    Return x.CompareTo(y)
                End If 
            End If 
        End If 
    End Function 
End Class 

Public Class Example

    Public Shared Sub Main()

        Dim dinosaurs As New List(Of String)
        dinosaurs.Add("Pachycephalosaurus")
        dinosaurs.Add("Amargasaurus")
        dinosaurs.Add("Mamenchisaurus")
        dinosaurs.Add("Deinonychus")
        Display(dinosaurs)

        Dim dc As New DinoComparer

        Console.WriteLine(vbLf & "Sort with alternate comparer:")
        dinosaurs.Sort(dc)
        Display(dinosaurs)

        SearchAndInsert(dinosaurs, "Coelophysis", dc)
        Display(dinosaurs)

        SearchAndInsert(dinosaurs, "Oviraptor", dc)
        Display(dinosaurs)

        SearchAndInsert(dinosaurs, "Tyrannosaur", dc)
        Display(dinosaurs)

        SearchAndInsert(dinosaurs, Nothing, dc)
        Display(dinosaurs)
    End Sub 

    Private Shared Sub SearchAndInsert( _
        ByVal lis As List(Of String), _
        ByVal insert As String, ByVal dc As DinoComparer)

        Console.WriteLine(vbLf & _
            "BinarySearch and Insert ""{0}"":", insert)

        Dim index As Integer = lis.BinarySearch(insert, dc)

        If index < 0 Then
            index = index Xor -1
            lis.Insert(index, insert)
        End If 
    End Sub 

    Private Shared Sub Display(ByVal lis As List(Of String))
        Console.WriteLine()
        For Each s As String In lis
            Console.WriteLine(s)
        Next 
    End Sub 
End Class 

' This code example produces the following output: 
' 
'Pachycephalosaurus 
'Amargasaurus 
'Mamenchisaurus 
'Deinonychus 
' 
'Sort with alternate comparer: 
' 
'Deinonychus 
'Amargasaurus 
'Mamenchisaurus 
'Pachycephalosaurus 
' 
'BinarySearch and Insert "Coelophysis": 
' 
'Coelophysis 
'Deinonychus 
'Amargasaurus 
'Mamenchisaurus 
'Pachycephalosaurus 
' 
'BinarySearch and Insert "Oviraptor": 
' 
'Oviraptor 
'Coelophysis 
'Deinonychus 
'Amargasaurus 
'Mamenchisaurus 
'Pachycephalosaurus 
' 
'BinarySearch and Insert "Tyrannosaur": 
' 
'Oviraptor 
'Coelophysis 
'Deinonychus 
'Tyrannosaur 
'Amargasaurus 
'Mamenchisaurus 
'Pachycephalosaurus 
' 
'BinarySearch and Insert "": 
' 
' 
'Oviraptor 
'Coelophysis 
'Deinonychus 
'Tyrannosaur 
'Amargasaurus 
'Mamenchisaurus 
'Pachycephalosaurus
using System;
using System.Collections.Generic;

public class DinoComparer: IComparer<string>
{
    public int Compare(string x, string y)
    {
        if (x == null)
        {
            if (y == null)
            {
                // If x is null and y is null, they're 
                // equal.  
                return 0;
            }
            else
            {
                // If x is null and y is not null, y 
                // is greater.  
                return -1;
            }
        }
        else
        {
            // If x is not null... 
            // 
            if (y == null)
                // ...and y is null, x is greater.
            {
                return 1;
            }
            else
            {
                // ...and y is not null, compare the  
                // lengths of the two strings. 
                // 
                int retval = x.Length.CompareTo(y.Length);

                if (retval != 0)
                {
                    // If the strings are not of equal length, 
                    // the longer string is greater. 
                    // 
                    return retval;
                }
                else
                {
                    // If the strings are of equal length, 
                    // sort them with ordinary string comparison. 
                    // 
                    return x.CompareTo(y);
                }
            }
        }
    }
}

public class Example
{
    public static void Main()
    {
        List<string> dinosaurs = new List<string>();
        dinosaurs.Add("Pachycephalosaurus");
        dinosaurs.Add("Amargasaurus");
        dinosaurs.Add("Mamenchisaurus");
        dinosaurs.Add("Deinonychus");
        Display(dinosaurs);

        DinoComparer dc = new DinoComparer();

        Console.WriteLine("\nSort with alternate comparer:");
        dinosaurs.Sort(dc);
        Display(dinosaurs);

        SearchAndInsert(dinosaurs, "Coelophysis", dc);
        Display(dinosaurs);

        SearchAndInsert(dinosaurs, "Oviraptor", dc);
        Display(dinosaurs);

        SearchAndInsert(dinosaurs, "Tyrannosaur", dc);
        Display(dinosaurs);

        SearchAndInsert(dinosaurs, null, dc);
        Display(dinosaurs);
    }

    private static void SearchAndInsert(List<string> list, 
        string insert, DinoComparer dc)
    {
        Console.WriteLine("\nBinarySearch and Insert \"{0}\":", insert);

        int index = list.BinarySearch(insert, dc);

        if (index < 0)
        {
            list.Insert(~index, insert);
        }
    }

    private static void Display(List<string> list)
    {
        Console.WriteLine();
        foreach( string s in list )
        {
            Console.WriteLine(s);
        }
    }
}

/* This code example produces the following output:

Pachycephalosaurus
Amargasaurus
Mamenchisaurus
Deinonychus

Sort with alternate comparer:

Deinonychus
Amargasaurus
Mamenchisaurus
Pachycephalosaurus

BinarySearch and Insert "Coelophysis":

Coelophysis
Deinonychus
Amargasaurus
Mamenchisaurus
Pachycephalosaurus

BinarySearch and Insert "Oviraptor":

Oviraptor
Coelophysis
Deinonychus
Amargasaurus
Mamenchisaurus
Pachycephalosaurus

BinarySearch and Insert "Tyrannosaur":

Oviraptor
Coelophysis
Deinonychus
Tyrannosaur
Amargasaurus
Mamenchisaurus
Pachycephalosaurus

BinarySearch and Insert "":


Oviraptor
Coelophysis
Deinonychus
Tyrannosaur
Amargasaurus
Mamenchisaurus
Pachycephalosaurus
 */
using namespace System;
using namespace System::Collections::Generic;

public ref class DinoComparer: IComparer<String^>
{
public:
    virtual int Compare(String^ x, String^ y)
    {
        if (x == nullptr)
        {
            if (y == nullptr)
            {
                // If x is null and y is null, they're 
                // equal.  
                return 0;
            }
            else
            {
                // If x is null and y is not null, y 
                // is greater.  
                return -1;
            }
        }
        else
        {
            // If x is not null... 
            // 
            if (y == nullptr)
                // ...and y is null, x is greater.
            {
                return 1;
            }
            else
            {
                // ...and y is not null, compare the  
                // lengths of the two strings. 
                // 
                int retval = x->Length.CompareTo(y->Length);

                if (retval != 0)
                {
                    // If the strings are not of equal length, 
                    // the longer string is greater. 
                    // 
                    return retval;
                }
                else
                {
                    // If the strings are of equal length, 
                    // sort them with ordinary string comparison. 
                    // 
                    return x->CompareTo(y);
                }
            }
        }
    }
};

void SearchAndInsert(List<String^>^ list, String^ insert, 
    DinoComparer^ dc)
{
    Console::WriteLine("\nBinarySearch and Insert \"{0}\":", insert);

    int index = list->BinarySearch(insert, dc);

    if (index < 0)
    {
        list->Insert(~index, insert);
    }
};

void Display(List<String^>^ list)
{
    Console::WriteLine();
    for each(String^ s in list)
    {
        Console::WriteLine(s);
    }
};

void main()
{
    List<String^>^ dinosaurs = gcnew List<String^>();
    dinosaurs->Add("Pachycephalosaurus");
    dinosaurs->Add("Amargasaurus");
    dinosaurs->Add("Mamenchisaurus");
    dinosaurs->Add("Deinonychus");
    Display(dinosaurs);

    DinoComparer^ dc = gcnew DinoComparer();

    Console::WriteLine("\nSort with alternate comparer:");
    dinosaurs->Sort(dc);
    Display(dinosaurs);

    SearchAndInsert(dinosaurs, "Coelophysis", dc);
    Display(dinosaurs);

    SearchAndInsert(dinosaurs, "Oviraptor", dc);
    Display(dinosaurs);

    SearchAndInsert(dinosaurs, "Tyrannosaur", dc);
    Display(dinosaurs);

    SearchAndInsert(dinosaurs, nullptr, dc);
    Display(dinosaurs);
}

/* This code example produces the following output:

Pachycephalosaurus
Amargasaurus
Mamenchisaurus
Deinonychus

Sort with alternate comparer:

Deinonychus
Amargasaurus
Mamenchisaurus
Pachycephalosaurus

BinarySearch and Insert "Coelophysis":

Coelophysis
Deinonychus
Amargasaurus
Mamenchisaurus
Pachycephalosaurus

BinarySearch and Insert "Oviraptor":

Oviraptor
Coelophysis
Deinonychus
Amargasaurus
Mamenchisaurus
Pachycephalosaurus

BinarySearch and Insert "Tyrannosaur":

Oviraptor
Coelophysis
Deinonychus
Tyrannosaur
Amargasaurus
Mamenchisaurus
Pachycephalosaurus

BinarySearch and Insert "":


Oviraptor
Coelophysis
Deinonychus
Tyrannosaur
Amargasaurus
Mamenchisaurus
Pachycephalosaurus
 */
Version Information

.NET Framework

Supported in: 4.5, 4, 3.5, 3.0, 2.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Portable Class Library

Supported in: Portable Class Library

.NET for Windows Store apps

Supported in: Windows 8
Platforms

Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.