Partager via


List<T>.BinarySearch Method (T, IComparer<T>)

Microsoft Silverlight will reach end of support after October 2021. Learn more.

Searches the entire sorted List<T> 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

'Declaration
Public Function BinarySearch ( _
    item As T, _
    comparer As IComparer(Of T) _
) As Integer
public int BinarySearch(
    T item,
    IComparer<T> comparer
)

Parameters

  • item
    Type: T
    The object to locate. The value can be nulla null reference (Nothing in Visual Basic) for reference types.

Return Value

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

Exception Condition
InvalidOperationException

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

Remarks

The comparer customizes how the elements are compared

If comparer is provided, the elements of the List<T> are compared to the specified value using the specified IComparer<T> implementation.

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

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

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

If the List<T> 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<T> 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<T>, 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(IComparer<T>) method overload and the BinarySearch(T, IComparer<T>) 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 nulla 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<T> 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, IComparer<T>) 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, IComparer<T>) and use it as an index for inserting the new string.

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 Demo(ByVal outputBlock As System.Windows.Controls.TextBlock)

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

      Dim dc As New DinoComparer

      outputBlock.Text &= vbLf & "Sort with alternate comparer:" & vbCrLf
      dinosaurs.Sort(dc)
      Display(outputBlock, dinosaurs)

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

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

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

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

   Private Shared Sub SearchAndInsert(ByVal outputBlock As System.Windows.Controls.TextBlock, _
       ByVal lis As List(Of String), _
       ByVal insert As String, ByVal dc As DinoComparer)

      outputBlock.Text &= String.Format(vbLf & _
          "BinarySearch and Insert ""{0}"":", insert) & vbCrLf

      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 outputBlock As System.Windows.Controls.TextBlock, ByVal lis As List(Of String))
      outputBlock.Text &= vbCrLf
      For Each s As String In lis
         outputBlock.Text &= s & vbCrLf
      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 Demo(System.Windows.Controls.TextBlock outputBlock)
   {
      List<string> dinosaurs = new List<string>();
      dinosaurs.Add("Pachycephalosaurus");
      dinosaurs.Add("Amargasaurus");
      dinosaurs.Add("Mamenchisaurus");
      dinosaurs.Add("Deinonychus");
      Display(outputBlock, dinosaurs);

      DinoComparer dc = new DinoComparer();

      outputBlock.Text += "\nSort with alternate comparer:" + "\n";
      dinosaurs.Sort(dc);
      Display(outputBlock, dinosaurs);

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

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

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

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

   private static void SearchAndInsert(System.Windows.Controls.TextBlock outputBlock, List<string> list,
       string insert, DinoComparer dc)
   {
      outputBlock.Text += String.Format("\nBinarySearch and Insert \"{0}\":", insert) + "\n";

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

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

   private static void Display(System.Windows.Controls.TextBlock outputBlock, List<string> list)
   {
      outputBlock.Text += "\n";
      foreach (string s in list)
      {
         outputBlock.Text += s + "\n";
      }
   }
}

/* 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

Silverlight

Supported in: 5, 4, 3

Silverlight for Windows Phone

Supported in: Windows Phone OS 7.1, Windows Phone OS 7.0

XNA Framework

Supported in: Xbox 360, Windows Phone OS 7.0

Platforms

For a list of the operating systems and browsers that are supported by Silverlight, see Supported Operating Systems and Browsers.