# List<T>.BinarySearchList<T>.BinarySearchList<T>.BinarySearchList<T>.BinarySearch Method

## 多載

 BinarySearch(T) BinarySearch(T) BinarySearch(T) BinarySearch(T) 使用預設的比較子並傳回項目以零為起始的索引，來搜尋項目之整個排序的 List。Searches the entire sorted List for an element using the default comparer and returns the zero-based index of the element. BinarySearch(T, IComparer) BinarySearch(T, IComparer) BinarySearch(T, IComparer) BinarySearch(T, IComparer) 使用指定的比較子並傳回項目以零為起始的索引，來搜尋項目之整個排序的 List。Searches the entire sorted List for an element using the specified comparer and returns the zero-based index of the element. BinarySearch(Int32, Int32, T, IComparer) BinarySearch(Int32, Int32, T, IComparer) BinarySearch(Int32, Int32, T, IComparer) BinarySearch(Int32, Int32, T, IComparer) 使用指定的比較子在已經過排序之 List 內，搜尋某範圍的項目，並傳回該項目以零為起始的索引。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.

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

``````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

### 範例

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

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

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

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)

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
``````

### 備註

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

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.

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

``````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

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

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

#### 例外狀況

`comparer``null`，而且預設比較子 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`.

### 範例

``````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^>();
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>();
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)
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
``````

### 備註

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

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.

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

``````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

count
Int32 Int32 Int32 Int32

item
T T T T

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

#### 例外狀況

`index` 小於 0。`index` is less than 0.

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

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

`comparer``null`，而且預設比較子 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`.

### 範例

The following example demonstrates the Sort(Int32, Int32, IComparer<T>) method overload and the BinarySearch(Int32, Int32, T, IComparer<T>) method overload.

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.

``````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^>();

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

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)

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
``````

### 備註

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

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.