List<T>.BinarySearch List<T>.BinarySearch List<T>.BinarySearch List<T>.BinarySearch Method

定義

使用二進位搜尋演算法來尋找在排序的 List<T> 中或在其中一部分中的特定項目。Uses a binary search algorithm to locate a specific element in the sorted List<T> or a portion of it.

多載

BinarySearch(T) BinarySearch(T) BinarySearch(T) BinarySearch(T)

使用預設的比較子並傳回項目以零為起始的索引,來搜尋項目之整個排序的 List<T>Searches the entire sorted List<T> for an element using the default comparer and returns the zero-based index of the element.

BinarySearch(T, IComparer<T>) BinarySearch(T, IComparer<T>) BinarySearch(T, IComparer<T>) BinarySearch(T, IComparer<T>)

使用指定的比較子並傳回項目以零為起始的索引,來搜尋項目之整個排序的 List<T>Searches the entire sorted List<T> for an element using the specified comparer and returns the zero-based index of the element.

BinarySearch(Int32, Int32, T, IComparer<T>) BinarySearch(Int32, Int32, T, IComparer<T>) BinarySearch(Int32, Int32, T, IComparer<T>) BinarySearch(Int32, Int32, T, IComparer<T>)

使用指定的比較子在已經過排序之 List<T> 內,搜尋某範圍的項目,並傳回該項目以零為起始的索引。Searches a range of elements in the sorted List<T> for an element using the specified comparer and returns the zero-based index of the element.

BinarySearch(T) BinarySearch(T) BinarySearch(T) BinarySearch(T)

使用預設的比較子並傳回項目以零為起始的索引,來搜尋項目之整個排序的 List<T>Searches the entire sorted List<T> for an element using the default comparer and returns the zero-based index of the element.

public:
 int BinarySearch(T item);
public int BinarySearch (T item);
member this.BinarySearch : 'T -> int
Public Function BinarySearch (item As T) As Integer

參數

item
T T T T

要尋找的物件。The object to locate. 參考類型的值可以是 nullThe value can be null for reference types.

傳回

如果有找到 item,則為已排序的 List<T>item 之以零為起始的索引,否則便為負數,此負數為大於 item 的下一個項目索引之位元補數,或者,如果沒有更大的項目,則為 Count 的位元補數。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.

例外狀況

預設比較子 Default 找不到 IComparable<T> 泛型介面的實作或型別 TIComparable 介面。The default comparer Default cannot find an implementation of the IComparable<T> generic interface or the IComparable interface for type T.

範例

下列範例示範Sort()方法多載BinarySearch(T)和方法多載。The following example demonstrates the Sort() method overload and the BinarySearch(T) method overload. 會建立字串的, 並以四個字串填入, 而不是特定的順序。List<T>A List<T> of strings is created and populated with four strings, in no particular order. 清單會顯示、排序並重新顯示。The list is displayed, sorted, and displayed again.

然後, Insert方法多載會用來搜尋不在清單中的兩個字串, 而方法則用來插入它們。 BinarySearch(T)The BinarySearch(T) method overload is then used to search for two strings that are not in the list, and the Insert method is used to insert them. 在每個案例中BinarySearch(T) , 方法的傳回值為負數, 因為字串不在清單中。The return value of the BinarySearch(T) method is negative in each case, because the strings are not in the list. 接受位補數 (中C#的 ~ 運算子和 Visual C++中的Xor -1, 在 Visual Basic 中), 會產生大於搜尋字串的清單中第一個元素的索引, 並在此位置插入保留排序次序。Taking the bitwise complement (the ~ operator in C# and Visual C++, Xor -1 in Visual Basic) of this negative number produces the index of the first element in the list that is larger than the search string, and inserting at this location preserves the sort order. 第二個搜尋字串大於清單中的任何元素, 因此插入位置位於清單的結尾。The second search string is larger than any element in the list, so the insertion position is at the end of the list.

using namespace System;
using namespace System::Collections::Generic;

void main()
{
    List<String^>^ dinosaurs = gcnew List<String^>();

    dinosaurs->Add("Pachycephalosaurus");
    dinosaurs->Add("Amargasaurus");
    dinosaurs->Add("Mamenchisaurus");
    dinosaurs->Add("Deinonychus");

    Console::WriteLine();
    for each(String^ dinosaur in dinosaurs)
    {
        Console::WriteLine(dinosaur);
    }

    Console::WriteLine("\nSort");
    dinosaurs->Sort();

    Console::WriteLine();
    for each(String^ dinosaur in dinosaurs)
    {
        Console::WriteLine(dinosaur);
    }

    Console::WriteLine("\nBinarySearch and Insert \"Coelophysis\":");
    int index = dinosaurs->BinarySearch("Coelophysis");
    if (index < 0)
    {
        dinosaurs->Insert(~index, "Coelophysis");
    }

    Console::WriteLine();
    for each(String^ dinosaur in dinosaurs)
    {
        Console::WriteLine(dinosaur);
    }

    Console::WriteLine("\nBinarySearch and Insert \"Tyrannosaurus\":");
    index = dinosaurs->BinarySearch("Tyrannosaurus");
    if (index < 0)
    {
        dinosaurs->Insert(~index, "Tyrannosaurus");
    }

    Console::WriteLine();
    for each(String^ dinosaur in dinosaurs)
    {
        Console::WriteLine(dinosaur);
    }
}

/* This code example produces the following output:

Pachycephalosaurus
Amargasaurus
Mamenchisaurus
Deinonychus

Sort

Amargasaurus
Deinonychus
Mamenchisaurus
Pachycephalosaurus

BinarySearch and Insert "Coelophysis":

Amargasaurus
Coelophysis
Deinonychus
Mamenchisaurus
Pachycephalosaurus

BinarySearch and Insert "Tyrannosaurus":

Amargasaurus
Coelophysis
Deinonychus
Mamenchisaurus
Pachycephalosaurus
Tyrannosaurus
 */
using System;
using System.Collections.Generic;

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");

        Console.WriteLine();
        foreach(string dinosaur in dinosaurs)
        {
            Console.WriteLine(dinosaur);
        }

        Console.WriteLine("\nSort");
        dinosaurs.Sort();

        Console.WriteLine();
        foreach(string dinosaur in dinosaurs)
        {
            Console.WriteLine(dinosaur);
        }

        Console.WriteLine("\nBinarySearch and Insert \"Coelophysis\":");
        int index = dinosaurs.BinarySearch("Coelophysis");
        if (index < 0)
        {
            dinosaurs.Insert(~index, "Coelophysis");
        }

        Console.WriteLine();
        foreach(string dinosaur in dinosaurs)
        {
            Console.WriteLine(dinosaur);
        }

        Console.WriteLine("\nBinarySearch and Insert \"Tyrannosaurus\":");
        index = dinosaurs.BinarySearch("Tyrannosaurus");
        if (index < 0)
        {
            dinosaurs.Insert(~index, "Tyrannosaurus");
        }

        Console.WriteLine();
        foreach(string dinosaur in dinosaurs)
        {
            Console.WriteLine(dinosaur);
        }
    }
}

/* This code example produces the following output:

Pachycephalosaurus
Amargasaurus
Mamenchisaurus
Deinonychus

Sort

Amargasaurus
Deinonychus
Mamenchisaurus
Pachycephalosaurus

BinarySearch and Insert "Coelophysis":

Amargasaurus
Coelophysis
Deinonychus
Mamenchisaurus
Pachycephalosaurus

BinarySearch and Insert "Tyrannosaurus":

Amargasaurus
Coelophysis
Deinonychus
Mamenchisaurus
Pachycephalosaurus
Tyrannosaurus
 */
Imports System
Imports System.Collections.Generic

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")

        Console.WriteLine()
        For Each dinosaur As String In dinosaurs
            Console.WriteLine(dinosaur)
        Next

        Console.WriteLine(vbLf & "Sort")
        dinosaurs.Sort

        Console.WriteLine()
        For Each dinosaur As String In dinosaurs
            Console.WriteLine(dinosaur)
        Next

        Console.WriteLine(vbLf & _
            "BinarySearch and Insert ""Coelophysis"":")
        Dim index As Integer = dinosaurs.BinarySearch("Coelophysis")
        If index < 0 Then
            index = index Xor -1
            dinosaurs.Insert(index, "Coelophysis")
        End If

        Console.WriteLine()
        For Each dinosaur As String In dinosaurs
            Console.WriteLine(dinosaur)
        Next

        Console.WriteLine(vbLf & _
            "BinarySearch and Insert ""Tyrannosaurus"":")
        index = dinosaurs.BinarySearch("Tyrannosaurus")
        If index < 0 Then
            index = index Xor -1
            dinosaurs.Insert(index, "Tyrannosaurus")
        End If

        Console.WriteLine()
        For Each dinosaur As String In dinosaurs
            Console.WriteLine(dinosaur)
        Next

    End Sub
End Class

' This code example produces the following output:
'
'Pachycephalosaurus
'Amargasaurus
'Mamenchisaurus
'Deinonychus
'
'Sort
'
'Amargasaurus
'Deinonychus
'Mamenchisaurus
'Pachycephalosaurus
'
'BinarySearch and Insert "Coelophysis":
'
'Amargasaurus
'Coelophysis
'Deinonychus
'Mamenchisaurus
'Pachycephalosaurus
'
'BinarySearch and Insert "Tyrannosaurus":
'
'Amargasaurus
'Coelophysis
'Deinonychus
'Mamenchisaurus
'Pachycephalosaurus
'Tyrannosaurus

備註

這個方法會使用類型Comparer<T>.Default T的預設比較子來決定清單元素的順序。This method uses the default comparer Comparer<T>.Default for type T to determine the order of list elements. 屬性會檢查類型T是否會執行IComparable<T>泛型介面, 並使用該實作為 (如果有的話)。 Comparer<T>.DefaultThe Comparer<T>.Default property checks whether type T implements the IComparable<T> generic interface and uses that implementation, if available. 如果不是Comparer<T>.Default , 則會T檢查類型IComparable是否會執行介面。If not, Comparer<T>.Default checks whether type T implements the IComparable interface. 如果類型T不會執行任一介面, Comparer<T>.DefaultInvalidOperationException會擲回。If type T does not implement either interface, Comparer<T>.Default throws an InvalidOperationException.

List<T>必須已根據比較子的實值排序, 否則結果會不正確。The List<T> must already be sorted according to the comparer implementation; otherwise, the result is incorrect.

使用泛型介面時, 允許與任何參考型別進行比較null , 且不會產生例外狀況。 IComparable<T>Comparing null with any reference type is allowed and does not generate an exception when using the IComparable<T> generic interface. 排序時, null會被視為小於任何其他物件。When sorting, null is considered to be less than any other object.

List<T>如果包含多個具有相同值的元素, 此方法只會傳回其中一個出現的專案, 而且可能會傳回任何出現的專案, 而不一定是第一個發生的。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.

List<T>如果不包含指定的值, 則方法會傳回負整數。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. 將值List<T>插入時, 應該使用這個索引做為插入點, 以維護排序次序。When inserting the value into the List<T>, this index should be used as the insertion point to maintain the sort order.

這個方法是 O (log n) 運算, 其中n是範圍中的元素數目。This method is an O(log n) operation, where n is the number of elements in the range.

另請參閱

BinarySearch(T, IComparer<T>) BinarySearch(T, IComparer<T>) BinarySearch(T, IComparer<T>) BinarySearch(T, IComparer<T>)

使用指定的比較子並傳回項目以零為起始的索引,來搜尋項目之整個排序的 List<T>Searches the entire sorted List<T> for an element using the specified comparer and returns the zero-based index of the element.

public:
 int BinarySearch(T item, System::Collections::Generic::IComparer<T> ^ comparer);
public int BinarySearch (T item, System.Collections.Generic.IComparer<T> comparer);
member this.BinarySearch : 'T * System.Collections.Generic.IComparer<'T> -> int
Public Function BinarySearch (item As T, comparer As IComparer(Of T)) As Integer

參數

item
T T T T

要尋找的物件。The object to locate. 參考類型的值可以是 nullThe value can be null for reference types.

comparer
IComparer<T> IComparer<T> IComparer<T> IComparer<T>

比較項目時所要使用的 IComparer<T> 實作。The IComparer<T> implementation to use when comparing elements.

-或--or- null 表示使用預設比較子 Defaultnull to use the default comparer Default.

傳回

如果有找到 item,則為已排序的 List<T>item 之以零為起始的索引,否則便為負數,此負數為大於 item 的下一個項目索引之位元補數,或者,如果沒有更大的項目,則為 Count 的位元補數。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.

例外狀況

comparernull,而且預設比較子 Default 找不到 IComparable<T> 泛型介面的實作或 T 類型的 IComparable 介面。comparer is null, and the default comparer Default cannot find an implementation of the IComparable<T> generic interface or the IComparable interface for type T.

範例

下列範例示範Sort(IComparer<T>)方法多載BinarySearch(T, IComparer<T>)和方法多載。The following example demonstrates the Sort(IComparer<T>) method overload and the BinarySearch(T, IComparer<T>) method overload.

此範例會針對名為 DinoCompare 的字串定義替代的比較子IComparer<string> ,IComparer(Of String)以執行 ( IComparer<String^>在 Visual C++) 泛型介面中的 (在 Visual Basic 中)。The 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. 比較子的運作方式如下:首先, 會測試null比較元數, 並將 null 參考視為小於非 null。The comparer works as follows: First, the comparands are tested for null, 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.

會建立字串的, 並以四個字串填入, 而不是特定的順序。List<T>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.

然後BinarySearch(T, IComparer<T>) , 方法多載會用來搜尋不在清單中的數個字串, 並採用替代的比較子。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. Insert方法是用來插入字串。The Insert method is used to insert the strings. 這兩個方法位於SearchAndInsert名為的函式中, 以及用來接受位補數的程式碼 (Visual Basic 中C++ Xor C#的 ~ 運算子) BinarySearch(T, IComparer<T>)和所傳回的負數, 並使用它做為插入新字串的索引。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.

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

備註

比較子會自訂元素的比較方式。The comparer customizes how the elements are compared. 例如, 您可以使用實例做CaseInsensitiveComparer為比較子來執行不區分大小寫的字串搜尋。For example, you can use a CaseInsensitiveComparer instance as the comparer to perform case-insensitive string searches.

如果comparer提供, 則List<T>會使用指定IComparer<T>的執行, 將的元素與指定的值進行比較。If comparer is provided, the elements of the List<T> are compared to the specified value using the specified IComparer<T> implementation.

如果comparernull, 則預設比較Comparer<T>.Default子會檢查T類型是否IComparable<T>會實作為泛型介面, 並使用該執行 (如果有的話)。If comparer is null, the default comparer Comparer<T>.Default checks whether type T implements the IComparable<T> generic interface and uses that implementation, if available. 如果不是Comparer<T>.Default , 則會T檢查類型IComparable是否會執行介面。If not, Comparer<T>.Default checks whether type T implements the IComparable interface. 如果類型T未執行任一介面, Comparer<T>.DefaultInvalidOperationException會擲回。If type T does not implement either interface, Comparer<T>.Default throws InvalidOperationException.

List<T>必須已根據比較子的實值排序, 否則結果會不正確。The List<T> must already be sorted according to the comparer implementation; otherwise, the result is incorrect.

使用泛型介面時, 允許與任何參考型別進行比較null , 且不會產生例外狀況。 IComparable<T>Comparing null with any reference type is allowed and does not generate an exception when using the IComparable<T> generic interface. 排序時, null會被視為小於任何其他物件。When sorting, null is considered to be less than any other object.

List<T>如果包含多個具有相同值的元素, 此方法只會傳回其中一個出現的專案, 而且可能會傳回任何出現的專案, 而不一定是第一個發生的。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.

List<T>如果不包含指定的值, 則方法會傳回負整數。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. 將值List<T>插入時, 應該使用這個索引做為插入點, 以維護排序次序。When inserting the value into the List<T>, this index should be used as the insertion point to maintain the sort order.

這個方法是 O (log n) 運算, 其中n是範圍中的元素數目。This method is an O(log n) operation, where n is the number of elements in the range.

另請參閱

BinarySearch(Int32, Int32, T, IComparer<T>) BinarySearch(Int32, Int32, T, IComparer<T>) BinarySearch(Int32, Int32, T, IComparer<T>) BinarySearch(Int32, Int32, T, IComparer<T>)

使用指定的比較子在已經過排序之 List<T> 內,搜尋某範圍的項目,並傳回該項目以零為起始的索引。Searches a range of elements in the sorted List<T> for an element using the specified comparer and returns the zero-based index of the element.

public:
 int BinarySearch(int index, int count, T item, System::Collections::Generic::IComparer<T> ^ comparer);
public int BinarySearch (int index, int count, T item, System.Collections.Generic.IComparer<T> comparer);
member this.BinarySearch : int * int * 'T * System.Collections.Generic.IComparer<'T> -> int
Public Function BinarySearch (index As Integer, count As Integer, item As T, comparer As IComparer(Of T)) As Integer

參數

index
Int32 Int32 Int32 Int32

要搜尋範圍內之以零為起始的起始索引。The zero-based starting index of the range to search.

count
Int32 Int32 Int32 Int32

搜尋範圍的長度。The length of the range to search.

item
T T T T

要尋找的物件。The object to locate. 參考類型的值可以是 nullThe value can be null for reference types.

comparer
IComparer<T> IComparer<T> IComparer<T> IComparer<T>

比較項目時要使用的 IComparer<T> 實作,或 null 表示使用預設比較子 DefaultThe IComparer<T> implementation to use when comparing elements, or null to use the default comparer Default.

傳回

如果有找到 item,則為已排序的 List<T>item 之以零為起始的索引,否則便為負數,此負數為大於 item 的下一個項目索引之位元補數,或者,如果沒有更大的項目,則為 Count 的位元補數。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.

例外狀況

index 小於 0。index is less than 0.

-或--or- count 小於 0。count is less than 0.

indexcount 不代表 List<T> 中的有效範圍。index and count do not denote a valid range in the List<T>.

comparernull,而且預設比較子 Default 找不到 IComparable<T> 泛型介面的實作或 T 類型的 IComparable 介面。comparer is null, and the default comparer Default cannot find an implementation of the IComparable<T> generic interface or the IComparable interface for type T.

範例

下列範例示範Sort(Int32, Int32, IComparer<T>)方法多載BinarySearch(Int32, Int32, T, IComparer<T>)和方法多載。The following example demonstrates the Sort(Int32, Int32, IComparer<T>) method overload and the BinarySearch(Int32, Int32, T, IComparer<T>) method overload.

此範例會針對名為 DinoCompare 的字串定義替代的比較子IComparer<string> ,IComparer(Of String)以執行 ( IComparer<String^>在 Visual C++) 泛型介面中的 (在 Visual Basic 中)。The 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. 比較子的運作方式如下:首先, 會測試null比較元數, 並將 null 參考視為小於非 null。The comparer works as follows: First, the comparands are tested for null, 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.

List<T>會建立字串的, 並以五個 herbivorous dinosaurs 和三個 carnivorous dinosaurs 的名稱填入。A List<T> 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. 隨即顯示清單, herbivores 的範圍會使用替代比較子進行排序, 而清單則會再次顯示。The list is displayed, the range of herbivores is sorted using the alternate comparer, and the list is displayed again.

然後BinarySearch(Int32, Int32, T, IComparer<T>) , 方法多載只會用來搜尋 "Brachiosaurus" 的 herbivores 範圍。The BinarySearch(Int32, Int32, T, IComparer<T>) method overload is then used to search only the range of herbivores for "Brachiosaurus". 找不到C#字串, 而且C++ Xor BinarySearch(Int32, Int32, T, IComparer<T>)方法所傳回之負數的位補數 (在 Visual Basic 中的 ~ 運算子) 是用來做為插入新字串的索引。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, IComparer<T>) method is used as an index for inserting the new string.

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 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("Parasauralophus");
    dinosaurs->Add("Amargasaurus");
    dinosaurs->Add("Galimimus");
    dinosaurs->Add("Mamenchisaurus");
    dinosaurs->Add("Deinonychus");
    dinosaurs->Add("Oviraptor");
    dinosaurs->Add("Tyrannosaurus");

    int herbivores = 5;
    Display(dinosaurs);

    DinoComparer^ dc = gcnew DinoComparer();

    Console::WriteLine("\nSort a range with the alternate comparer:");
    dinosaurs->Sort(0, herbivores, dc);
    Display(dinosaurs);

    Console::WriteLine("\nBinarySearch a range and Insert \"{0}\":",
            "Brachiosaurus");

    int index = dinosaurs->BinarySearch(0, herbivores, "Brachiosaurus", dc);

    if (index < 0)
    {
        dinosaurs->Insert(~index, "Brachiosaurus");
        herbivores++;
    }

    Display(dinosaurs);
}

/* This code example produces the following output:

Pachycephalosaurus
Parasauralophus
Amargasaurus
Galimimus
Mamenchisaurus
Deinonychus
Oviraptor
Tyrannosaurus

Sort a range with the alternate comparer:

Galimimus
Amargasaurus
Mamenchisaurus
Parasauralophus
Pachycephalosaurus
Deinonychus
Oviraptor
Tyrannosaurus

BinarySearch a range and Insert "Brachiosaurus":

Galimimus
Amargasaurus
Brachiosaurus
Mamenchisaurus
Parasauralophus
Pachycephalosaurus
Deinonychus
Oviraptor
Tyrannosaurus
 */
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("Parasauralophus");
        dinosaurs.Add("Amargasaurus");
        dinosaurs.Add("Galimimus");
        dinosaurs.Add("Mamenchisaurus");
        dinosaurs.Add("Deinonychus");
        dinosaurs.Add("Oviraptor");
        dinosaurs.Add("Tyrannosaurus");

        int herbivores = 5;
        Display(dinosaurs);

        DinoComparer dc = new DinoComparer();

        Console.WriteLine("\nSort a range with the alternate comparer:");
        dinosaurs.Sort(0, herbivores, dc);
        Display(dinosaurs);

        Console.WriteLine("\nBinarySearch a range and Insert \"{0}\":",
            "Brachiosaurus");

        int index = dinosaurs.BinarySearch(0, herbivores, "Brachiosaurus", dc);

        if (index < 0)
        {
            dinosaurs.Insert(~index, "Brachiosaurus");
            herbivores++;
        }

        Display(dinosaurs);
    }

    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
Parasauralophus
Amargasaurus
Galimimus
Mamenchisaurus
Deinonychus
Oviraptor
Tyrannosaurus

Sort a range with the alternate comparer:

Galimimus
Amargasaurus
Mamenchisaurus
Parasauralophus
Pachycephalosaurus
Deinonychus
Oviraptor
Tyrannosaurus

BinarySearch a range and Insert "Brachiosaurus":

Galimimus
Amargasaurus
Brachiosaurus
Mamenchisaurus
Parasauralophus
Pachycephalosaurus
Deinonychus
Oviraptor
Tyrannosaurus
 */
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("Parasauralophus")
        dinosaurs.Add("Amargasaurus")
        dinosaurs.Add("Galimimus")
        dinosaurs.Add("Mamenchisaurus")
        dinosaurs.Add("Deinonychus")
        dinosaurs.Add("Oviraptor")
        dinosaurs.Add("Tyrannosaurus")

        Dim herbivores As Integer = 5
        Display(dinosaurs)

        Dim dc As New DinoComparer

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

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

        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

        Display(dinosaurs)

    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
'Parasauralophus
'Amargasaurus
'Galimimus
'Mamenchisaurus
'Deinonychus
'Oviraptor
'Tyrannosaurus
'
'Sort a range with the alternate comparer:
'
'Galimimus
'Amargasaurus
'Mamenchisaurus
'Parasauralophus
'Pachycephalosaurus
'Deinonychus
'Oviraptor
'Tyrannosaurus
'
'BinarySearch a range and Insert "Brachiosaurus":
'
'Galimimus
'Amargasaurus
'Brachiosaurus
'Mamenchisaurus
'Parasauralophus
'Pachycephalosaurus
'Deinonychus
'Oviraptor
'Tyrannosaurus

備註

比較子會自訂元素的比較方式。The comparer customizes how the elements are compared. 例如, 您可以使用實例做CaseInsensitiveComparer為比較子來執行不區分大小寫的字串搜尋。For example, you can use a CaseInsensitiveComparer instance as the comparer to perform case-insensitive string searches.

如果comparer提供, 則List<T>會使用指定IComparer<T>的執行, 將的元素與指定的值進行比較。If comparer is provided, the elements of the List<T> are compared to the specified value using the specified IComparer<T> implementation.

如果comparernull, 則預設比較Comparer<T>.Default子會檢查T類型是否IComparable<T>會實作為泛型介面, 並使用該執行 (如果有的話)。If comparer is null, the default comparer Comparer<T>.Default checks whether type T implements the IComparable<T> generic interface and uses that implementation, if available. 如果不是Comparer<T>.Default , 則會T檢查類型IComparable是否會執行介面。If not, Comparer<T>.Default checks whether type T implements the IComparable interface. 如果類型T未執行任一介面, Comparer<T>.DefaultInvalidOperationException會擲回。If type T does not implement either interface, Comparer<T>.Default throws InvalidOperationException.

List<T>必須已根據比較子的實值排序, 否則結果會不正確。The List<T> must already be sorted according to the comparer implementation; otherwise, the result is incorrect.

使用泛型介面時, 允許與任何參考型別進行比較null , 且不會產生例外狀況。 IComparable<T>Comparing null with any reference type is allowed and does not generate an exception when using the IComparable<T> generic interface. 排序時, null會被視為小於任何其他物件。When sorting, null is considered to be less than any other object.

List<T>如果包含多個具有相同值的元素, 此方法只會傳回其中一個出現的專案, 而且可能會傳回任何出現的專案, 而不一定是第一個發生的。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.

List<T>如果不包含指定的值, 則方法會傳回負整數。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. 將值List<T>插入時, 應該使用這個索引做為插入點, 以維護排序次序。When inserting the value into the List<T>, this index should be used as the insertion point to maintain the sort order.

這個方法是 O (log n) 運算, 其中n是範圍中的元素數目。This method is an O(log n) operation, where n is the number of elements in the range.

另請參閱

適用於