List<T>.BinarySearch Método
Definición
Sobrecargas
BinarySearch(T) |
Busca la List<T> completa ordenada para un elemento usando el comparador predeterminado y devuelve el índice de base cero del elemento.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>) |
Busca la List<T> completa ordenada para un elemento usando el comparador especificado y devuelve el índice de base cero del elemento.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>) |
Busca un elemento en un intervalo de elementos del objeto List<T> ordenado usando el comparador especificado y devuelve el índice de base cero del elemento.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)
public:
int BinarySearch(T item);
public int BinarySearch (T item);
member this.BinarySearch : 'T -> int
Public Function BinarySearch (item As T) As Integer
Parámetros
- item
- T
Objeto que se va a buscar.The object to locate. El valor puede ser null
para los tipos de referencia.The value can be null
for reference types.
Devoluciones
Índice de base cero de item
en la List<T> ordenada, si es que se encuentra item
; en caso contrario, número negativo que es el complemento bit a bit del índice del siguiente elemento mayor que item
o, si no hay ningún elemento mayor, el complemento bit a bit de 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.
Excepciones
El comparador predeterminado Default no puede encontrar una implementación de la interfaz genérica IComparable<T> o la interfaz IComparable del tipo T
.The default comparer Default cannot find an implementation of the IComparable<T> generic interface or the IComparable interface for type T
.
Ejemplos
En el ejemplo siguiente se muestra la Sort() sobrecarga del método y la BinarySearch(T) sobrecarga del método.The following example demonstrates the Sort() method overload and the BinarySearch(T) method overload. Un List<T> de cadenas se crea y rellena con cuatro cadenas, en ningún orden determinado.A List<T> of strings is created and populated with four strings, in no particular order. La lista se muestra, se ordena y se muestra de nuevo.The list is displayed, sorted, and displayed again.
La BinarySearch(T) sobrecarga del método se utiliza para buscar dos cadenas que no están en la lista y el Insert método se usa para insertarlas.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. El valor devuelto del BinarySearch(T) método es negativo en cada caso, porque las cadenas no están en la lista.The return value of the BinarySearch(T) method is negative in each case, because the strings are not in the list. Al tomar el complemento bit a bit (el operador ~ en C# y Visual C++, Xor
-1 en Visual Basic) de este número negativo, se genera el índice del primer elemento de la lista que es mayor que la cadena de búsqueda, y la inserción en esta ubicación conserva el criterio de ordenación.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. La segunda cadena de búsqueda es mayor que cualquier elemento de la lista, por lo que la posición de inserción se encuentra al final de la lista.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
*/
List<string> dinosaurs = new List<string>();
dinosaurs.Add("Pachycephalosaurus");
dinosaurs.Add("Amargasaurus");
dinosaurs.Add("Mamenchisaurus");
dinosaurs.Add("Deinonychus");
Console.WriteLine("Initial list:");
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:
Initial list:
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.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
Comentarios
Este método utiliza el comparador predeterminado Comparer<T>.Default para T
el tipo con el fin de determinar el orden de los elementos de lista.This method uses the default comparer Comparer<T>.Default for type T
to determine the order of list elements. La Comparer<T>.Default propiedad comprueba si T
el tipo implementa la IComparable<T> interfaz genérica y utiliza esa implementación, si está disponible.The Comparer<T>.Default property checks whether type T
implements the IComparable<T> generic interface and uses that implementation, if available. Si no es así, Comparer<T>.Default comprueba si T
el tipo implementa la IComparable interfaz.If not, Comparer<T>.Default checks whether type T
implements the IComparable interface. Si el tipo no T
implementa ninguna de las interfaces, Comparer<T>.Default produce una excepción InvalidOperationException .If type T
does not implement either interface, Comparer<T>.Default throws an InvalidOperationException.
El List<T> ya debe estar ordenado según la implementación del comparador; de lo contrario, el resultado es incorrecto.The List<T> must already be sorted according to the comparer implementation; otherwise, the result is incorrect.
null
Se permite comparar con cualquier tipo de referencia y no genera una excepción cuando se usa la IComparable<T> interfaz genérica.Comparing null
with any reference type is allowed and does not generate an exception when using the IComparable<T> generic interface. Al ordenar, null
se considera que es menor que cualquier otro objeto.When sorting, null
is considered to be less than any other object.
Si List<T> contiene más de un elemento con el mismo valor, el método solo devuelve una de las repeticiones y puede devolver cualquiera de las apariciones, no necesariamente la primera.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.
Si no List<T> contiene el valor especificado, el método devuelve un entero negativo.If the List<T> does not contain the specified value, the method returns a negative integer. Puede aplicar la operación de complemento bit a bit (~) a este entero negativo para obtener el índice del primer elemento que sea mayor que el valor de búsqueda.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. Al insertar el valor en List<T> , este índice se debe utilizar como punto de inserción para mantener el criterio de ordenación.When inserting the value into the List<T>, this index should be used as the insertion point to maintain the sort order.
Este método es una operación O (log n), donde n es el número de elementos del intervalo.This method is an O(log n) operation, where n is the number of elements in the range.
Consulte también
Se aplica a
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);
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
Parámetros
- item
- T
Objeto que se va a buscar.The object to locate. El valor puede ser null
para los tipos de referencia.The value can be null
for reference types.
- comparer
- IComparer<T>
Implementación de IComparer<T> que se va a usar al comparar elementos.The IComparer<T> implementation to use when comparing elements.
o bien-or-
null
para utilizar el comparador predeterminado Default.null
to use the default comparer Default.
Devoluciones
Índice de base cero de item
en la List<T> ordenada, si es que se encuentra item
; en caso contrario, número negativo que es el complemento bit a bit del índice del siguiente elemento mayor que item
o, si no hay ningún elemento mayor, el complemento bit a bit de 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.
Excepciones
comparer
es null
, y el comparador predeterminado Default no puede encontrar una implementación de la interfaz genérica IComparable<T> o la interfaz IComparable del tipo T
.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
.
Ejemplos
En el ejemplo siguiente se muestra la Sort(IComparer<T>) sobrecarga del método y la BinarySearch(T, IComparer<T>) sobrecarga del método.The following example demonstrates the Sort(IComparer<T>) method overload and the BinarySearch(T, IComparer<T>) method overload.
En el ejemplo se define un comparador alternativo para las cadenas denominadas DinoCompare, que implementa la IComparer<string>
IComparer(Of String)
interfaz genérica (en Visual Basic, IComparer<String^>
en Visual C++).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. El comparador funciona de la siguiente manera: en primer lugar, se prueban los términos de comparación null
y se trata una referencia nula como menor que un valor no 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. En segundo lugar, se comparan las longitudes de cadena y se considera que la cadena más larga es mayor.Second, the string lengths are compared, and the longer string is deemed to be greater. En tercer lugar, si las longitudes son iguales, se usa la comparación de cadenas ordinaria.Third, if the lengths are equal, ordinary string comparison is used.
Un List<T> de cadenas se crea y rellena con cuatro cadenas, en ningún orden determinado.A List<T> of strings is created and populated with four strings, in no particular order. La lista se muestra, se ordena mediante el comparador alternativo y se muestra de nuevo.The list is displayed, sorted using the alternate comparer, and displayed again.
BinarySearch(T, IComparer<T>)A continuación, la sobrecarga del método se utiliza para buscar varias cadenas que no están en la lista, empleando el comparador alternativo.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. El Insert método se usa para insertar las cadenas.The Insert method is used to insert the strings. Estos dos métodos se encuentran en la función denominada SearchAndInsert
, junto con el código para tomar el complemento bit a bit (el operador ~ en C# y Visual C++, Xor
-1 en Visual Basic) del número negativo devuelto por BinarySearch(T, IComparer<T>) y usarlo como índice para insertar la nueva cadena.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.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
Comentarios
El comparador Personaliza el modo en que se comparan los elementos.The comparer customizes how the elements are compared. Por ejemplo, puede usar una CaseInsensitiveComparer instancia como comparador para realizar búsquedas de cadenas que no distinguen entre mayúsculas y minúsculas.For example, you can use a CaseInsensitiveComparer instance as the comparer to perform case-insensitive string searches.
Si comparer
se proporciona, los elementos de se comparan con List<T> el valor especificado mediante la IComparer<T> implementación de especificada.If comparer
is provided, the elements of the List<T> are compared to the specified value using the specified IComparer<T> implementation.
Si comparer
es null
, el comparador predeterminado Comparer<T>.Default comprueba si T
el tipo implementa la IComparable<T> interfaz genérica y utiliza esa implementación, si está disponible.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. Si no es así, Comparer<T>.Default comprueba si T
el tipo implementa la IComparable interfaz.If not, Comparer<T>.Default checks whether type T
implements the IComparable interface. Si el tipo no T
implementa ninguna de las interfaces, Comparer<T>.Default produce una excepción InvalidOperationException .If type T
does not implement either interface, Comparer<T>.Default throws InvalidOperationException.
El List<T> ya debe estar ordenado según la implementación del comparador; de lo contrario, el resultado es incorrecto.The List<T> must already be sorted according to the comparer implementation; otherwise, the result is incorrect.
null
Se permite comparar con cualquier tipo de referencia y no genera una excepción cuando se usa la IComparable<T> interfaz genérica.Comparing null
with any reference type is allowed and does not generate an exception when using the IComparable<T> generic interface. Al ordenar, null
se considera que es menor que cualquier otro objeto.When sorting, null
is considered to be less than any other object.
Si List<T> contiene más de un elemento con el mismo valor, el método solo devuelve una de las repeticiones y puede devolver cualquiera de las apariciones, no necesariamente la primera.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.
Si no List<T> contiene el valor especificado, el método devuelve un entero negativo.If the List<T> does not contain the specified value, the method returns a negative integer. Puede aplicar la operación de complemento bit a bit (~) a este entero negativo para obtener el índice del primer elemento que sea mayor que el valor de búsqueda.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. Al insertar el valor en List<T> , este índice se debe utilizar como punto de inserción para mantener el criterio de ordenación.When inserting the value into the List<T>, this index should be used as the insertion point to maintain the sort order.
Este método es una operación O (log n), donde n es el número de elementos del intervalo.This method is an O(log n) operation, where n is the number of elements in the range.
Consulte también
Se aplica a
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);
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
Parámetros
- index
- Int32
Índice inicial de base cero del intervalo que se va a buscar.The zero-based starting index of the range to search.
- count
- Int32
Longitud del intervalo en el que se va a buscar.The length of the range to search.
- item
- T
Objeto que se va a buscar.The object to locate. El valor puede ser null
para los tipos de referencia.The value can be null
for reference types.
- comparer
- IComparer<T>
Implementación de IComparer<T> que se va a utilizar al comparar elementos, o null
para utilizar el comparador predeterminado Default.The IComparer<T> implementation to use when comparing elements, or null
to use the default comparer Default.
Devoluciones
Índice de base cero de item
en la List<T> ordenada, si es que se encuentra item
; en caso contrario, número negativo que es el complemento bit a bit del índice del siguiente elemento mayor que item
o, si no hay ningún elemento mayor, el complemento bit a bit de 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.
Excepciones
index
es menor que 0.index
is less than 0.
o bien-or-
count
es menor que 0.count
is less than 0.
index
y count
no denotan un intervalo válido en List<T>.index
and count
do not denote a valid range in the List<T>.
comparer
es null
, y el comparador predeterminado Default no puede encontrar una implementación de la interfaz genérica IComparable<T> o la interfaz IComparable del tipo T
.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
.
Ejemplos
En el ejemplo siguiente se muestra la Sort(Int32, Int32, IComparer<T>) sobrecarga del método y la BinarySearch(Int32, Int32, T, IComparer<T>) sobrecarga del método.The following example demonstrates the Sort(Int32, Int32, IComparer<T>) method overload and the BinarySearch(Int32, Int32, T, IComparer<T>) method overload.
En el ejemplo se define un comparador alternativo para las cadenas denominadas DinoCompare, que implementa la IComparer<string>
IComparer(Of String)
interfaz genérica (en Visual Basic, IComparer<String^>
en Visual C++).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. El comparador funciona de la siguiente manera: en primer lugar, se prueban los términos de comparación null
y se trata una referencia nula como menor que un valor no 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. En segundo lugar, se comparan las longitudes de cadena y se considera que la cadena más larga es mayor.Second, the string lengths are compared, and the longer string is deemed to be greater. En tercer lugar, si las longitudes son iguales, se usa la comparación de cadenas ordinaria.Third, if the lengths are equal, ordinary string comparison is used.
Un List<T> de cadenas se crea y rellena con los nombres de cinco dinosaurios herbivorous y tres dinosaurios de carnívoros.A List<T> of strings is created and populated with the names of five herbivorous dinosaurs and three carnivorous dinosaurs. Dentro de cada uno de los dos grupos, los nombres no se encuentran en ningún criterio de ordenación determinado.Within each of the two groups, the names are not in any particular sort order. Se muestra la lista, el intervalo de herbivores se ordena mediante el comparador alternativo y la lista se muestra de nuevo.The list is displayed, the range of herbivores is sorted using the alternate comparer, and the list is displayed again.
La BinarySearch(Int32, Int32, T, IComparer<T>) sobrecarga del método se usa para buscar solo el intervalo de herbivores para "Brachiosaurus".The BinarySearch(Int32, Int32, T, IComparer<T>) method overload is then used to search only the range of herbivores for "Brachiosaurus". No se encuentra la cadena y el complemento bit a bit (el operador ~ en C# y Visual C++, Xor
-1 en Visual Basic) del número negativo devuelto por el BinarySearch(Int32, Int32, T, IComparer<T>) método se utiliza como índice para insertar la nueva cadena.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.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
Comentarios
El comparador Personaliza el modo en que se comparan los elementos.The comparer customizes how the elements are compared. Por ejemplo, puede usar una CaseInsensitiveComparer instancia como comparador para realizar búsquedas de cadenas que no distinguen entre mayúsculas y minúsculas.For example, you can use a CaseInsensitiveComparer instance as the comparer to perform case-insensitive string searches.
Si comparer
se proporciona, los elementos de se comparan con List<T> el valor especificado mediante la IComparer<T> implementación de especificada.If comparer
is provided, the elements of the List<T> are compared to the specified value using the specified IComparer<T> implementation.
Si comparer
es null
, el comparador predeterminado Comparer<T>.Default comprueba si T
el tipo implementa la IComparable<T> interfaz genérica y utiliza esa implementación, si está disponible.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. Si no es así, Comparer<T>.Default comprueba si T
el tipo implementa la IComparable interfaz.If not, Comparer<T>.Default checks whether type T
implements the IComparable interface. Si el tipo no T
implementa ninguna de las interfaces, Comparer<T>.Default produce una excepción InvalidOperationException .If type T
does not implement either interface, Comparer<T>.Default throws InvalidOperationException.
El List<T> ya debe estar ordenado según la implementación del comparador; de lo contrario, el resultado es incorrecto.The List<T> must already be sorted according to the comparer implementation; otherwise, the result is incorrect.
null
Se permite comparar con cualquier tipo de referencia y no genera una excepción cuando se usa la IComparable<T> interfaz genérica.Comparing null
with any reference type is allowed and does not generate an exception when using the IComparable<T> generic interface. Al ordenar, null
se considera que es menor que cualquier otro objeto.When sorting, null
is considered to be less than any other object.
Si List<T> contiene más de un elemento con el mismo valor, el método solo devuelve una de las repeticiones y puede devolver cualquiera de las apariciones, no necesariamente la primera.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.
Si no List<T> contiene el valor especificado, el método devuelve un entero negativo.If the List<T> does not contain the specified value, the method returns a negative integer. Puede aplicar la operación de complemento bit a bit (~) a este entero negativo para obtener el índice del primer elemento que sea mayor que el valor de búsqueda.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. Al insertar el valor en List<T> , este índice se debe utilizar como punto de inserción para mantener el criterio de ordenación.When inserting the value into the List<T>, this index should be used as the insertion point to maintain the sort order.
Este método es una operación O (log n), donde n es el número de elementos del intervalo.This method is an O(log n) operation, where n is the number of elements in the range.
Consulte también
- IComparer<T>
- IComparable<T>
- Realizar operaciones de cadenas que no tienen en cuenta las referencias culturales en coleccionesPerforming Culture-Insensitive String Operations in Collections