This documentation is archived and is not being maintained.

List.BinarySearch Method (Int32, Int32, T, Generic IComparer)

Searches a range of elements in the sorted List 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)

Public Function BinarySearch ( _
	index As Integer, _
	count As Integer, _
	item As T, _
	comparer As IComparer(Of T) _
) As Integer
Dim instance As List(Of T)
Dim index As Integer
Dim count As Integer
Dim item As T
Dim comparer As IComparer(Of T)
Dim returnValue As Integer

returnValue = instance.BinarySearch(index, count, item, comparer)
public int BinarySearch (
	int index, 
	int count, 
	T item, 
	IComparer<T> comparer
public function BinarySearch (
	index : int, 
	count : int, 
	item : T, 
	comparer : IComparer<T>
) : int
Not applicable.



The zero-based starting index of the range to search.


The length of the range to search.


The object to locate. The value can be a null reference (Nothing in Visual Basic) for reference types.


The IComparer implementation to use when comparing elements, or a null reference (Nothing in Visual Basic) to use the default comparer Comparer.Default.

Return Value

The zero-based index of item in the sorted List, 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.

Exception typeCondition


index is less than 0.


count is less than 0.


index and count do not denote a valid range in the List.


comparer is a null reference (Nothing in Visual Basic), and the default comparer Comparer.Default cannot find an implementation of the IComparable generic interface or the IComparable interface for type T.

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 List are compared to the specified value using the specified IComparer implementation.

If comparer is a null reference (Nothing in Visual Basic), the default comparer Comparer.Default checks whether type T implements the IComparable generic interface and uses that implementation, if available. If not, Comparer.Default checks whether type T implements the IComparable interface. If type T does not implement either interface, Comparer.Default throws InvalidOperationException.

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

Comparing a null reference (Nothing in Visual Basic) with any reference type is allowed and does not generate an exception when using the IComparable generic interface. When sorting, a null reference (Nothing in Visual Basic) is considered to be less than any other object.

If the List 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 List 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 List, 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.

The following code example demonstrates the Sort(Int32,Int32,Generic IComparer) method overload and the BinarySearch(Int32,Int32,T,Generic IComparer) 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 a null reference (Nothing in Visual Basic), 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 List of strings is created and populated with the names of five herbivorous dinosaurs and three carnivorous dinosaurs. Within each of the two groups, the names are not in any particular sort order. The list is displayed, the range of herbivores is sorted using the alternate comparer, and the list is displayed again.

The BinarySearch(Int32,Int32,T,Generic IComparer) method overload is then used to search only the range of herbivores for "Brachiosaurus". The string is not found, and the bitwise complement (the ~ operator in C# and Visual C++, Xor -1 in Visual Basic) of the negative number returned by the BinarySearch(Int32,Int32,T,Generic IComparer) method is used 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
                ' If x is Nothing and y is not Nothing, y
                ' is greater. 
                Return -1
            End If
            ' If x is not Nothing...
            If y Is Nothing Then
                ' ...and y is Nothing, x is greater.
                Return 1
                ' ...and y is not Nothing, compare the 
                ' lengths of the two strings.
                Dim retval As Integer = _

                If retval <> 0 Then 
                    ' If the strings are not of equal length,
                    ' the longer string is greater.
                    Return retval
                    ' 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)


        Dim herbivores As Integer = 5

        Dim dc As New DinoComparer

        Console.WriteLine(vbLf & _
            "Sort a range with the alternate comparer:")
        dinosaurs.Sort(0, herbivores, dc)

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

        Dim index As Integer = _
            dinosaurs.BinarySearch(0, herbivores, "Brachiosaurus", dc)

        If index < 0 Then
            index = index Xor -1
            dinosaurs.Insert(index, "Brachiosaurus")
            herbivores += 1
        End If


    End Sub

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

' This code example produces the following output:
'Sort a range with the alternate comparer:
'BinarySearch a range and Insert "Brachiosaurus":

Windows 98, Windows Server 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

The Microsoft .NET Framework 3.0 is supported on Windows Vista, Microsoft Windows XP SP2, and Windows Server 2003 SP1.

.NET Framework

Supported in: 3.0, 2.0

.NET Compact Framework

Supported in: 2.0

XNA Framework

Supported in: 1.0