Array.IndexOf Método

Definición

Busca el objeto especificado y devuelve el índice de la primera aparición en una matriz unidimensional o en un intervalo de elementos de la matriz.

Sobrecargas

IndexOf(Array, Object)

Busca el objeto especificado y devuelve el índice de su primera aparición en una matriz unidimensional.

IndexOf(Array, Object, Int32)

Busca el objeto especificado en un intervalo de elementos de una matriz unidimensional y devuelve el índice de su primera aparición. El intervalo abarca desde un índice especificado hasta el final de la matriz.

IndexOf(Array, Object, Int32, Int32)

Busca el objeto especificado en un intervalo de elementos de una matriz unidimensional y devuelve el índice de su primera aparición. El intervalo se extiende desde un índice especificado durante un número especificado de elementos.

IndexOf<T>(T[], T, Int32)

Busca el objeto especificado en un intervalo de elementos de una matriz unidimensional y devuelve el índice de su primera aparición. El intervalo abarca desde un índice especificado hasta el final de la matriz.

IndexOf<T>(T[], T, Int32, Int32)

Busca el objeto especificado en un intervalo de elementos de una matriz unidimensional y devuelve el índice de su primera aparición. El intervalo se extiende desde un índice especificado durante un número especificado de elementos.

IndexOf<T>(T[], T)

Busca el objeto especificado y devuelve el índice de su primera aparición en una matriz unidimensional.

IndexOf(Array, Object)

Busca el objeto especificado y devuelve el índice de su primera aparición en una matriz unidimensional.

public:
 static int IndexOf(Array ^ array, System::Object ^ value);
public static int IndexOf (Array array, object value);
public static int IndexOf (Array array, object? value);
static member IndexOf : Array * obj -> int
Public Shared Function IndexOf (array As Array, value As Object) As Integer

Parámetros

array
Array

Matriz unidimensional en la que se va a buscar.

value
Object

Objeto que se va a buscar en array.

Devoluciones

Índice de la primera aparición de value en la matriz array, si se encuentra; en caso contrario, límite inferior de la matriz menos 1.

Excepciones

array es null.

array es multidimensional.

Ejemplos

En el ejemplo se llama a las tres sobrecargas siguientes del IndexOf método para buscar el índice de una cadena en una matriz de cadenas:

  • IndexOf(Array, Object), para determinar la primera aparición de la cadena "the" en una matriz de cadenas.

  • IndexOf(Array, Object, Int32), para determinar la primera aparición de la cadena "the" en el cuarto a los últimos elementos de una matriz de cadenas.

  • IndexOf(Array, Object, Int32, Int32), para determinar la primera aparición de la cadena "the" en una matriz de cadenas del elemento que sigue la última coincidencia correcta al final de la matriz.

using namespace System;

void main()
{
   // Create a string array with 3 elements having the same value.
   array<String^>^ strings = { "the", "quick", "brown", "fox",
                               "jumps", "over", "the", "lazy", "dog",
                               "in", "the", "barn" };

   // Display the elements of the array.
   Console::WriteLine("The array contains the following values:");
   for (int i = strings->GetLowerBound(0); i <= strings->GetUpperBound(0); i++)
      Console::WriteLine("   [{0,2}]: {1}", i, strings[i]);
      
   // Search for the first occurrence of the duplicated value.
   String^ searchString =  "the";
   int index = Array::IndexOf(strings, searchString);
   Console::WriteLine("The first occurrence of \"{0}\" is at index {1}.",
                      searchString, index);

   // Search for the first occurrence of the duplicated value in the last section of the array.
   index = Array::IndexOf( strings, searchString, 4);
   Console::WriteLine("The first occurrence of \"{0}\" between index 4 and the end is at index {1}.",
                      searchString, index);

   // Search for the first occurrence of the duplicated value in a section of the array.
   int position = index + 1;
   index = Array::IndexOf(strings, searchString, position, strings->GetUpperBound(0) - position + 1);
   Console::WriteLine("The first occurrence of \"{0}\" between index {1} and index {2} is at index {3}.",
                      searchString, position, strings->GetUpperBound(0), index);
}
// The example displays the following output:
//    The array contains the following values:
//       [ 0]: the
//       [ 1]: quick
//       [ 2]: brown
//       [ 3]: fox
//       [ 4]: jumps
//       [ 5]: over
//       [ 6]: the
//       [ 7]: lazy
//       [ 8]: dog
//       [ 9]: in
//       [10]: the
//       [11]: barn
//    The first occurrence of "the" is at index 0.
//    The first occurrence of "the" between index 4 and the end is at index 6.
//    The first occurrence of "the" between index 7 and index 11 is at index 10.
// Create a string array with 3 elements having the same value.
let strings = 
    [| "the"; "quick"; "brown"; "fox"; "jumps"; "over"
       "the"; "lazy"; "dog"; "in"; "the"; "barn" |]

// Display the elements of the array.
printfn "The array contains the following values:"
for i = strings.GetLowerBound 0 to strings.GetUpperBound 0 do
    printfn $"   [{i,2}]: {strings[i]}"

// Search for the first occurrence of the duplicated value.
let searchString = "the"
let index = Array.IndexOf(strings, searchString)
printfn $"The first occurrence of \"{searchString}\" is at index {index}."

// Search for the first occurrence of the duplicated value in the last section of the array.
let index = Array.IndexOf(strings, searchString, 4)
printfn $"The first occurrence of \"{searchString}\" between index 4 and the end is at index {index}."

// Search for the first occurrence of the duplicated value in a section of the array.
let position = index + 1
let index = Array.IndexOf(strings, searchString, position, strings.GetUpperBound 0 - position + 1)
printfn $"The first occurrence of \"{searchString}\" between index {position} and index {strings.GetUpperBound 0} is at index {index}."

// The example displays the following output:
//    The array contains the following values:
//       [ 0]: the
//       [ 1]: quick
//       [ 2]: brown
//       [ 3]: fox
//       [ 4]: jumps
//       [ 5]: over
//       [ 6]: the
//       [ 7]: lazy
//       [ 8]: dog
//       [ 9]: in
//       [10]: the
//       [11]: barn
//    The first occurrence of "the" is at index 0.
//    The first occurrence of "the" between index 4 and the end is at index 6.
//    The first occurrence of "the" between index 7 and index 11 is at index 10.
// Create a string array with 3 elements having the same value.
String[] strings = { "the", "quick", "brown", "fox", "jumps",
                     "over", "the", "lazy", "dog", "in", "the",
                     "barn" };

// Display the elements of the array.
Console.WriteLine("The array contains the following values:");
for (int i = strings.GetLowerBound(0); i <= strings.GetUpperBound(0); i++)
   Console.WriteLine("   [{0,2}]: {1}", i, strings[i]);

// Search for the first occurrence of the duplicated value.
string searchString = "the";
int index = Array.IndexOf(strings, searchString);
Console.WriteLine("The first occurrence of \"{0}\" is at index {1}.",
                  searchString, index);

// Search for the first occurrence of the duplicated value in the last section of the array.
index = Array.IndexOf(strings, searchString, 4);
Console.WriteLine("The first occurrence of \"{0}\" between index 4 and the end is at index {1}.",
                  searchString, index);

// Search for the first occurrence of the duplicated value in a section of the array.
int position = index + 1;
index = Array.IndexOf(strings, searchString, position, strings.GetUpperBound(0) - position + 1);
Console.WriteLine("The first occurrence of \"{0}\" between index {1} and index {2} is at index {3}.",
                  searchString, position, strings.GetUpperBound(0), index);

// The example displays the following output:
//    The array contains the following values:
//       [ 0]: the
//       [ 1]: quick
//       [ 2]: brown
//       [ 3]: fox
//       [ 4]: jumps
//       [ 5]: over
//       [ 6]: the
//       [ 7]: lazy
//       [ 8]: dog
//       [ 9]: in
//       [10]: the
//       [11]: barn
//    The first occurrence of "the" is at index 0.
//    The first occurrence of "the" between index 4 and the end is at index 6.
//    The first occurrence of "the" between index 7 and index 11 is at index 10.
Public Module Example
   Public Sub Main()
      ' Create a string array with 3 elements having the same value.
      Dim strings() As String = { "the", "quick", "brown", "fox",
                                  "jumps", "over", "the", "lazy",
                                  "dog", "in", "the", "barn" }

      ' Display the values of the array.
      Console.WriteLine("The array contains the following values:")
      For i As Integer = strings.GetLowerBound(0) To strings.GetUpperBound(0)
         Console.WriteLine("   [{0,2}]: {1}", i, strings(i))
      Next

      ' Search for the first occurrence of the duplicated value.
      Dim searchString As String = "the"
      Dim index As Integer = Array.IndexOf(strings, searchString)
      Console.WriteLine("The first occurrence of ""{0}"" is at index {1}.",
                        searchString, index)
        
      ' Search for the first occurrence of the duplicated value in the last section of the array.
      index = Array.IndexOf(strings, searchString, 4)
      Console.WriteLine("The first occurrence of ""{0}"" between index 4 and the end is at index {1}.",
                        searchString, index)
        
      ' Search for the first occurrence of the duplicated value in a section of the array.
       Dim position As Integer = index + 1
       index = Array.IndexOf(strings, searchString, position, strings.GetUpperBound(0) - position + 1)
       Console.WriteLine("The first occurrence of ""{0}"" between index {1} and index {2} is at index {3}.",
                         searchString, position, strings.GetUpperBound(0), index)
    End Sub
End Module
' The example displays the following output:
'    The array contains the following values:
'       [ 0]: the
'       [ 1]: quick
'       [ 2]: brown
'       [ 3]: fox
'       [ 4]: jumps
'       [ 5]: over
'       [ 6]: the
'       [ 7]: lazy
'       [ 8]: dog
'       [ 9]: in
'       [10]: the
'       [11]: barn
'    The first occurrence of "the" is at index 0.
'    The first occurrence of "the" between index 4 and the end is at index 6.
'    The first occurrence of "the" between index 7 and index 11 is at index 10.

Comentarios

Este método busca en todos los elementos de una matriz valueunidimensional . Para determinar si value existe en array, el método realiza una comparación de igualdad llamando al método de Equals cada elemento hasta que encuentre una coincidencia. Esto significa que si el elemento invalida el Object.Equals(Object) método , se llama a esa invalidación.

Dado que la mayoría de las matrices tienen un límite inferior de cero, este método suele devolver -1 sivalue no se encuentra. En el caso poco frecuente de que el límite inferior de la matriz sea igual a Int32.MinValue(0x80000000) y value no se encuentre, este método devuelve Int32.MaxValue (0x7FFFFFFF).

Este método es una operación O(n), donde n es el Length de array.

Consulte también

Se aplica a

IndexOf(Array, Object, Int32)

Busca el objeto especificado en un intervalo de elementos de una matriz unidimensional y devuelve el índice de su primera aparición. El intervalo abarca desde un índice especificado hasta el final de la matriz.

public:
 static int IndexOf(Array ^ array, System::Object ^ value, int startIndex);
public static int IndexOf (Array array, object value, int startIndex);
public static int IndexOf (Array array, object? value, int startIndex);
static member IndexOf : Array * obj * int -> int
Public Shared Function IndexOf (array As Array, value As Object, startIndex As Integer) As Integer

Parámetros

array
Array

Matriz unidimensional en la que se va a buscar.

value
Object

Objeto que se va a buscar en array.

startIndex
Int32

Índice inicial de la búsqueda. 0 (cero) es válido en una matriz vacía.

Devoluciones

Índice de la primera aparición de value, si se encuentra, dentro del intervalo de elementos de array que abarca desde startIndex hasta el último elemento; de lo contrario, límite inferior de la matriz menos 1.

Excepciones

array es null.

startIndex está fuera del intervalo de índices válidos para la array.

array es multidimensional.

Ejemplos

En el ejemplo se llama a las tres sobrecargas siguientes del IndexOf método para buscar el índice de una cadena en una matriz de cadenas:

  • IndexOf(Array, Object), para determinar la primera aparición de la cadena "the" en una matriz de cadenas.

  • IndexOf(Array, Object, Int32), para determinar la primera aparición de la cadena "the" en el cuarto a los últimos elementos de una matriz de cadenas.

  • IndexOf(Array, Object, Int32, Int32), para determinar la primera aparición de la cadena "the" en una matriz de cadenas del elemento que sigue la última coincidencia correcta al final de la matriz.

using namespace System;

void main()
{
   // Create a string array with 3 elements having the same value.
   array<String^>^ strings = { "the", "quick", "brown", "fox",
                               "jumps", "over", "the", "lazy", "dog",
                               "in", "the", "barn" };

   // Display the elements of the array.
   Console::WriteLine("The array contains the following values:");
   for (int i = strings->GetLowerBound(0); i <= strings->GetUpperBound(0); i++)
      Console::WriteLine("   [{0,2}]: {1}", i, strings[i]);
      
   // Search for the first occurrence of the duplicated value.
   String^ searchString =  "the";
   int index = Array::IndexOf(strings, searchString);
   Console::WriteLine("The first occurrence of \"{0}\" is at index {1}.",
                      searchString, index);

   // Search for the first occurrence of the duplicated value in the last section of the array.
   index = Array::IndexOf( strings, searchString, 4);
   Console::WriteLine("The first occurrence of \"{0}\" between index 4 and the end is at index {1}.",
                      searchString, index);

   // Search for the first occurrence of the duplicated value in a section of the array.
   int position = index + 1;
   index = Array::IndexOf(strings, searchString, position, strings->GetUpperBound(0) - position + 1);
   Console::WriteLine("The first occurrence of \"{0}\" between index {1} and index {2} is at index {3}.",
                      searchString, position, strings->GetUpperBound(0), index);
}
// The example displays the following output:
//    The array contains the following values:
//       [ 0]: the
//       [ 1]: quick
//       [ 2]: brown
//       [ 3]: fox
//       [ 4]: jumps
//       [ 5]: over
//       [ 6]: the
//       [ 7]: lazy
//       [ 8]: dog
//       [ 9]: in
//       [10]: the
//       [11]: barn
//    The first occurrence of "the" is at index 0.
//    The first occurrence of "the" between index 4 and the end is at index 6.
//    The first occurrence of "the" between index 7 and index 11 is at index 10.
// Create a string array with 3 elements having the same value.
let strings = 
    [| "the"; "quick"; "brown"; "fox"; "jumps"; "over"
       "the"; "lazy"; "dog"; "in"; "the"; "barn" |]

// Display the elements of the array.
printfn "The array contains the following values:"
for i = strings.GetLowerBound 0 to strings.GetUpperBound 0 do
    printfn $"   [{i,2}]: {strings[i]}"

// Search for the first occurrence of the duplicated value.
let searchString = "the"
let index = Array.IndexOf(strings, searchString)
printfn $"The first occurrence of \"{searchString}\" is at index {index}."

// Search for the first occurrence of the duplicated value in the last section of the array.
let index = Array.IndexOf(strings, searchString, 4)
printfn $"The first occurrence of \"{searchString}\" between index 4 and the end is at index {index}."

// Search for the first occurrence of the duplicated value in a section of the array.
let position = index + 1
let index = Array.IndexOf(strings, searchString, position, strings.GetUpperBound 0 - position + 1)
printfn $"The first occurrence of \"{searchString}\" between index {position} and index {strings.GetUpperBound 0} is at index {index}."

// The example displays the following output:
//    The array contains the following values:
//       [ 0]: the
//       [ 1]: quick
//       [ 2]: brown
//       [ 3]: fox
//       [ 4]: jumps
//       [ 5]: over
//       [ 6]: the
//       [ 7]: lazy
//       [ 8]: dog
//       [ 9]: in
//       [10]: the
//       [11]: barn
//    The first occurrence of "the" is at index 0.
//    The first occurrence of "the" between index 4 and the end is at index 6.
//    The first occurrence of "the" between index 7 and index 11 is at index 10.
// Create a string array with 3 elements having the same value.
String[] strings = { "the", "quick", "brown", "fox", "jumps",
                     "over", "the", "lazy", "dog", "in", "the",
                     "barn" };

// Display the elements of the array.
Console.WriteLine("The array contains the following values:");
for (int i = strings.GetLowerBound(0); i <= strings.GetUpperBound(0); i++)
   Console.WriteLine("   [{0,2}]: {1}", i, strings[i]);

// Search for the first occurrence of the duplicated value.
string searchString = "the";
int index = Array.IndexOf(strings, searchString);
Console.WriteLine("The first occurrence of \"{0}\" is at index {1}.",
                  searchString, index);

// Search for the first occurrence of the duplicated value in the last section of the array.
index = Array.IndexOf(strings, searchString, 4);
Console.WriteLine("The first occurrence of \"{0}\" between index 4 and the end is at index {1}.",
                  searchString, index);

// Search for the first occurrence of the duplicated value in a section of the array.
int position = index + 1;
index = Array.IndexOf(strings, searchString, position, strings.GetUpperBound(0) - position + 1);
Console.WriteLine("The first occurrence of \"{0}\" between index {1} and index {2} is at index {3}.",
                  searchString, position, strings.GetUpperBound(0), index);

// The example displays the following output:
//    The array contains the following values:
//       [ 0]: the
//       [ 1]: quick
//       [ 2]: brown
//       [ 3]: fox
//       [ 4]: jumps
//       [ 5]: over
//       [ 6]: the
//       [ 7]: lazy
//       [ 8]: dog
//       [ 9]: in
//       [10]: the
//       [11]: barn
//    The first occurrence of "the" is at index 0.
//    The first occurrence of "the" between index 4 and the end is at index 6.
//    The first occurrence of "the" between index 7 and index 11 is at index 10.
Public Module Example
   Public Sub Main()
      ' Create a string array with 3 elements having the same value.
      Dim strings() As String = { "the", "quick", "brown", "fox",
                                  "jumps", "over", "the", "lazy",
                                  "dog", "in", "the", "barn" }

      ' Display the values of the array.
      Console.WriteLine("The array contains the following values:")
      For i As Integer = strings.GetLowerBound(0) To strings.GetUpperBound(0)
         Console.WriteLine("   [{0,2}]: {1}", i, strings(i))
      Next

      ' Search for the first occurrence of the duplicated value.
      Dim searchString As String = "the"
      Dim index As Integer = Array.IndexOf(strings, searchString)
      Console.WriteLine("The first occurrence of ""{0}"" is at index {1}.",
                        searchString, index)
        
      ' Search for the first occurrence of the duplicated value in the last section of the array.
      index = Array.IndexOf(strings, searchString, 4)
      Console.WriteLine("The first occurrence of ""{0}"" between index 4 and the end is at index {1}.",
                        searchString, index)
        
      ' Search for the first occurrence of the duplicated value in a section of the array.
       Dim position As Integer = index + 1
       index = Array.IndexOf(strings, searchString, position, strings.GetUpperBound(0) - position + 1)
       Console.WriteLine("The first occurrence of ""{0}"" between index {1} and index {2} is at index {3}.",
                         searchString, position, strings.GetUpperBound(0), index)
    End Sub
End Module
' The example displays the following output:
'    The array contains the following values:
'       [ 0]: the
'       [ 1]: quick
'       [ 2]: brown
'       [ 3]: fox
'       [ 4]: jumps
'       [ 5]: over
'       [ 6]: the
'       [ 7]: lazy
'       [ 8]: dog
'       [ 9]: in
'       [10]: the
'       [11]: barn
'    The first occurrence of "the" is at index 0.
'    The first occurrence of "the" between index 4 and the end is at index 6.
'    The first occurrence of "the" between index 7 and index 11 is at index 10.

Comentarios

Este método busca una matriz unidimensional desde el elemento en el índice startIndex hasta el último elemento. Para determinar si value existe en array, el método realiza una comparación de igualdad llamando al Equals método de cada elemento hasta que encuentre una coincidencia. Esto significa que si el elemento invalida el Object.Equals(Object) método , se llama a esa invalidación.

Dado que la mayoría de las matrices tienen un límite inferior de cero, este método suele devolver -1 si value no se encuentra. En el caso poco frecuente de que el límite inferior de la matriz sea igual a Int32.MinValue(0x80000000) y value no se encuentre, este método devuelve Int32.MaxValue (0x7FFFFFFF).

Si startIndex es igual a Array.Length, el método devuelve -1. Si startIndex es mayor que Array.Length, el método produce una ArgumentOutOfRangeExceptionexcepción .

Este método es una operación O(n), donde n es el número de elementos de startIndex hasta el final de array.

Consulte también

Se aplica a

IndexOf(Array, Object, Int32, Int32)

Busca el objeto especificado en un intervalo de elementos de una matriz unidimensional y devuelve el índice de su primera aparición. El intervalo se extiende desde un índice especificado durante un número especificado de elementos.

public:
 static int IndexOf(Array ^ array, System::Object ^ value, int startIndex, int count);
public static int IndexOf (Array array, object value, int startIndex, int count);
public static int IndexOf (Array array, object? value, int startIndex, int count);
static member IndexOf : Array * obj * int * int -> int
Public Shared Function IndexOf (array As Array, value As Object, startIndex As Integer, count As Integer) As Integer

Parámetros

array
Array

Matriz unidimensional en la que se va a buscar.

value
Object

Objeto que se va a buscar en array.

startIndex
Int32

Índice inicial de la búsqueda. 0 (cero) es válido en una matriz vacía.

count
Int32

Número de elementos que se van a buscar.

Devoluciones

Índice de la primera aparición de value, si se encuentra, en array desde el índice startIndex hasta startIndex + count - 1; de lo contrario, límite inferior de la matriz menos 1.

Excepciones

array es null.

startIndex está fuera del intervalo de índices válidos para la array.

o bien

count es menor que cero.

o bien

startIndex y count no especifican una sección válida en array.

array es multidimensional.

Ejemplos

En el ejemplo se llama a las tres sobrecargas siguientes del IndexOf método para buscar el índice de una cadena en una matriz de cadenas:

  • IndexOf(Array, Object), para determinar la primera aparición de la cadena "the" en una matriz de cadenas.

  • IndexOf(Array, Object, Int32), para determinar la primera aparición de la cadena "the" en el cuarto a los últimos elementos de una matriz de cadenas.

  • IndexOf(Array, Object, Int32, Int32), para determinar la primera aparición de la cadena "the" en una matriz de cadenas del elemento que sigue la última coincidencia correcta al final de la matriz. Para determinar el valor del count argumento, resta el límite superior de la matriz del índice inicial y agrega uno.

using namespace System;

void main()
{
   // Create a string array with 3 elements having the same value.
   array<String^>^ strings = { "the", "quick", "brown", "fox",
                               "jumps", "over", "the", "lazy", "dog",
                               "in", "the", "barn" };

   // Display the elements of the array.
   Console::WriteLine("The array contains the following values:");
   for (int i = strings->GetLowerBound(0); i <= strings->GetUpperBound(0); i++)
      Console::WriteLine("   [{0,2}]: {1}", i, strings[i]);
      
   // Search for the first occurrence of the duplicated value.
   String^ searchString =  "the";
   int index = Array::IndexOf(strings, searchString);
   Console::WriteLine("The first occurrence of \"{0}\" is at index {1}.",
                      searchString, index);

   // Search for the first occurrence of the duplicated value in the last section of the array.
   index = Array::IndexOf( strings, searchString, 4);
   Console::WriteLine("The first occurrence of \"{0}\" between index 4 and the end is at index {1}.",
                      searchString, index);

   // Search for the first occurrence of the duplicated value in a section of the array.
   int position = index + 1;
   index = Array::IndexOf(strings, searchString, position, strings->GetUpperBound(0) - position + 1);
   Console::WriteLine("The first occurrence of \"{0}\" between index {1} and index {2} is at index {3}.",
                      searchString, position, strings->GetUpperBound(0), index);
}
// The example displays the following output:
//    The array contains the following values:
//       [ 0]: the
//       [ 1]: quick
//       [ 2]: brown
//       [ 3]: fox
//       [ 4]: jumps
//       [ 5]: over
//       [ 6]: the
//       [ 7]: lazy
//       [ 8]: dog
//       [ 9]: in
//       [10]: the
//       [11]: barn
//    The first occurrence of "the" is at index 0.
//    The first occurrence of "the" between index 4 and the end is at index 6.
//    The first occurrence of "the" between index 7 and index 11 is at index 10.
// Create a string array with 3 elements having the same value.
let strings = 
    [| "the"; "quick"; "brown"; "fox"; "jumps"; "over"
       "the"; "lazy"; "dog"; "in"; "the"; "barn" |]

// Display the elements of the array.
printfn "The array contains the following values:"
for i = strings.GetLowerBound 0 to strings.GetUpperBound 0 do
    printfn $"   [{i,2}]: {strings[i]}"

// Search for the first occurrence of the duplicated value.
let searchString = "the"
let index = Array.IndexOf(strings, searchString)
printfn $"The first occurrence of \"{searchString}\" is at index {index}."

// Search for the first occurrence of the duplicated value in the last section of the array.
let index = Array.IndexOf(strings, searchString, 4)
printfn $"The first occurrence of \"{searchString}\" between index 4 and the end is at index {index}."

// Search for the first occurrence of the duplicated value in a section of the array.
let position = index + 1
let index = Array.IndexOf(strings, searchString, position, strings.GetUpperBound 0 - position + 1)
printfn $"The first occurrence of \"{searchString}\" between index {position} and index {strings.GetUpperBound 0} is at index {index}."

// The example displays the following output:
//    The array contains the following values:
//       [ 0]: the
//       [ 1]: quick
//       [ 2]: brown
//       [ 3]: fox
//       [ 4]: jumps
//       [ 5]: over
//       [ 6]: the
//       [ 7]: lazy
//       [ 8]: dog
//       [ 9]: in
//       [10]: the
//       [11]: barn
//    The first occurrence of "the" is at index 0.
//    The first occurrence of "the" between index 4 and the end is at index 6.
//    The first occurrence of "the" between index 7 and index 11 is at index 10.
// Create a string array with 3 elements having the same value.
String[] strings = { "the", "quick", "brown", "fox", "jumps",
                     "over", "the", "lazy", "dog", "in", "the",
                     "barn" };

// Display the elements of the array.
Console.WriteLine("The array contains the following values:");
for (int i = strings.GetLowerBound(0); i <= strings.GetUpperBound(0); i++)
   Console.WriteLine("   [{0,2}]: {1}", i, strings[i]);

// Search for the first occurrence of the duplicated value.
string searchString = "the";
int index = Array.IndexOf(strings, searchString);
Console.WriteLine("The first occurrence of \"{0}\" is at index {1}.",
                  searchString, index);

// Search for the first occurrence of the duplicated value in the last section of the array.
index = Array.IndexOf(strings, searchString, 4);
Console.WriteLine("The first occurrence of \"{0}\" between index 4 and the end is at index {1}.",
                  searchString, index);

// Search for the first occurrence of the duplicated value in a section of the array.
int position = index + 1;
index = Array.IndexOf(strings, searchString, position, strings.GetUpperBound(0) - position + 1);
Console.WriteLine("The first occurrence of \"{0}\" between index {1} and index {2} is at index {3}.",
                  searchString, position, strings.GetUpperBound(0), index);

// The example displays the following output:
//    The array contains the following values:
//       [ 0]: the
//       [ 1]: quick
//       [ 2]: brown
//       [ 3]: fox
//       [ 4]: jumps
//       [ 5]: over
//       [ 6]: the
//       [ 7]: lazy
//       [ 8]: dog
//       [ 9]: in
//       [10]: the
//       [11]: barn
//    The first occurrence of "the" is at index 0.
//    The first occurrence of "the" between index 4 and the end is at index 6.
//    The first occurrence of "the" between index 7 and index 11 is at index 10.
Public Module Example
   Public Sub Main()
      ' Create a string array with 3 elements having the same value.
      Dim strings() As String = { "the", "quick", "brown", "fox",
                                  "jumps", "over", "the", "lazy",
                                  "dog", "in", "the", "barn" }

      ' Display the values of the array.
      Console.WriteLine("The array contains the following values:")
      For i As Integer = strings.GetLowerBound(0) To strings.GetUpperBound(0)
         Console.WriteLine("   [{0,2}]: {1}", i, strings(i))
      Next

      ' Search for the first occurrence of the duplicated value.
      Dim searchString As String = "the"
      Dim index As Integer = Array.IndexOf(strings, searchString)
      Console.WriteLine("The first occurrence of ""{0}"" is at index {1}.",
                        searchString, index)
        
      ' Search for the first occurrence of the duplicated value in the last section of the array.
      index = Array.IndexOf(strings, searchString, 4)
      Console.WriteLine("The first occurrence of ""{0}"" between index 4 and the end is at index {1}.",
                        searchString, index)
        
      ' Search for the first occurrence of the duplicated value in a section of the array.
       Dim position As Integer = index + 1
       index = Array.IndexOf(strings, searchString, position, strings.GetUpperBound(0) - position + 1)
       Console.WriteLine("The first occurrence of ""{0}"" between index {1} and index {2} is at index {3}.",
                         searchString, position, strings.GetUpperBound(0), index)
    End Sub
End Module
' The example displays the following output:
'    The array contains the following values:
'       [ 0]: the
'       [ 1]: quick
'       [ 2]: brown
'       [ 3]: fox
'       [ 4]: jumps
'       [ 5]: over
'       [ 6]: the
'       [ 7]: lazy
'       [ 8]: dog
'       [ 9]: in
'       [10]: the
'       [11]: barn
'    The first occurrence of "the" is at index 0.
'    The first occurrence of "the" between index 4 and the end is at index 6.
'    The first occurrence of "the" between index 7 and index 11 is at index 10.

Comentarios

Este método busca los elementos de una matriz unidimensional de startIndex a startIndexcount más menos 1, si count es mayor que 0. Para determinar si value existe en array, el método realiza una comparación de igualdad llamando al Equals método de cada elemento hasta que encuentre una coincidencia. Esto significa que si el elemento invalida el Object.Equals método , se llama a esa invalidación.

Dado que la mayoría de las matrices tienen un límite inferior de cero, este método suele devolver -1 cuando value no se encuentra. En el caso raro de que el límite inferior de la matriz sea igual a Int32.MinValue (0x80000000) y value no se encuentre, este método devuelve Int32.MaxValue (0x7FFFFFFF).

Si startindex es igual a Array.Length, el método devuelve -1. Si startIndex es mayor que Array.Length, el método produce una ArgumentOutOfRangeExceptionexcepción .

Este método es una operación O(n), donde n es count.

Consulte también

Se aplica a

IndexOf<T>(T[], T, Int32)

Busca el objeto especificado en un intervalo de elementos de una matriz unidimensional y devuelve el índice de su primera aparición. El intervalo abarca desde un índice especificado hasta el final de la matriz.

public:
generic <typename T>
 static int IndexOf(cli::array <T> ^ array, T value, int startIndex);
public static int IndexOf<T> (T[] array, T value, int startIndex);
static member IndexOf : 'T[] * 'T * int -> int
Public Shared Function IndexOf(Of T) (array As T(), value As T, startIndex As Integer) As Integer

Parámetros de tipo

T

Tipo de los elementos de la matriz.

Parámetros

array
T[]

Matriz unidimensional de base cero en la que se va a buscar.

value
T

Objeto que se va a buscar en array.

startIndex
Int32

Índice inicial de base cero de la búsqueda. 0 (cero) es válido en una matriz vacía.

Devoluciones

Índice de base cero de la primera aparición de value dentro del intervalo de elementos de la matriz array que abarca desde startIndex hasta el último elemento, si se encuentra; de lo contrario, -1.

Excepciones

array es null.

startIndex está fuera del intervalo de índices válidos para la array.

Ejemplos

En el ejemplo siguiente se muestran las tres sobrecargas genéricas del IndexOf método . Se crea una matriz de cadenas, con una entrada que aparece dos veces, en la ubicación del índice 0 y la ubicación del índice 5. La IndexOf<T>(T[], T) sobrecarga del método busca la matriz desde el principio y busca la primera aparición de la cadena. La IndexOf<T>(T[], T, Int32) sobrecarga del método se usa para buscar en la matriz a partir de la ubicación del índice 3 y continuar hasta el final de la matriz, y busca la segunda aparición de la cadena. Por último, la sobrecarga del IndexOf<T>(T[], T, Int32, Int32) método se usa para buscar en un intervalo de dos entradas, comenzando en la ubicación del índice dos; devuelve -1 porque no hay instancias de la cadena de búsqueda en ese intervalo.

using namespace System;

void main()
{
    array<String^>^ dinosaurs = { "Tyrannosaurus", 
        "Amargasaurus",
        "Mamenchisaurus",
        "Brachiosaurus",
        "Deinonychus",
        "Tyrannosaurus",
        "Compsognathus" };

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

    Console::WriteLine("\nArray.IndexOf(dinosaurs, \"Tyrannosaurus\"): {0}", 
        Array::IndexOf(dinosaurs, "Tyrannosaurus"));

    Console::WriteLine("\nArray.IndexOf(dinosaurs, \"Tyrannosaurus\", 3): {0}", 
        Array::IndexOf(dinosaurs, "Tyrannosaurus", 3));

    Console::WriteLine("\nArray.IndexOf(dinosaurs, \"Tyrannosaurus\", 2, 2): {0}", 
        Array::IndexOf(dinosaurs, "Tyrannosaurus", 2, 2));
}

/* This code example produces the following output:

Tyrannosaurus
Amargasaurus
Mamenchisaurus
Brachiosaurus
Deinonychus
Tyrannosaurus
Compsognathus

Array.IndexOf(dinosaurs, "Tyrannosaurus"): 0

Array.IndexOf(dinosaurs, "Tyrannosaurus", 3): 5

Array.IndexOf(dinosaurs, "Tyrannosaurus", 2, 2): -1
 */
string[] dinosaurs = { "Tyrannosaurus",
    "Amargasaurus",
    "Mamenchisaurus",
    "Brachiosaurus",
    "Deinonychus",
    "Tyrannosaurus",
    "Compsognathus" };

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

Console.WriteLine(
    "\nArray.IndexOf(dinosaurs, \"Tyrannosaurus\"): {0}",
    Array.IndexOf(dinosaurs, "Tyrannosaurus"));

Console.WriteLine(
    "\nArray.IndexOf(dinosaurs, \"Tyrannosaurus\", 3): {0}",
    Array.IndexOf(dinosaurs, "Tyrannosaurus", 3));

Console.WriteLine(
    "\nArray.IndexOf(dinosaurs, \"Tyrannosaurus\", 2, 2): {0}",
    Array.IndexOf(dinosaurs, "Tyrannosaurus", 2, 2));

/* This code example produces the following output:

Tyrannosaurus
Amargasaurus
Mamenchisaurus
Brachiosaurus
Deinonychus
Tyrannosaurus
Compsognathus

Array.IndexOf(dinosaurs, "Tyrannosaurus"): 0

Array.IndexOf(dinosaurs, "Tyrannosaurus", 3): 5

Array.IndexOf(dinosaurs, "Tyrannosaurus", 2, 2): -1
*/
open System

let dinosaurs =
    [| "Tyrannosaurus"
       "Amargasaurus"
       "Mamenchisaurus"
       "Brachiosaurus"
       "Deinonychus"
       "Tyrannosaurus"
       "Compsognathus" |]

printfn ""
for dino in dinosaurs do
    printfn $"{dino}"

Array.IndexOf(dinosaurs, "Tyrannosaurus")
|> printfn "\nArray.IndexOf(dinosaurs, \"Tyrannosaurus\"): %i"

Array.IndexOf(dinosaurs, "Tyrannosaurus", 3)
|> printfn "\nArray.IndexOf(dinosaurs, \"Tyrannosaurus\", 3): %i"

Array.IndexOf(dinosaurs, "Tyrannosaurus", 2, 2)
|> printfn "\nArray.IndexOf(dinosaurs, \"Tyrannosaurus\", 2, 2): %i"

// This code example produces the following output:
//
//    Tyrannosaurus
//    Amargasaurus
//    Mamenchisaurus
//    Brachiosaurus
//    Deinonychus
//    Tyrannosaurus
//    Compsognathus
//    
//    Array.IndexOf(dinosaurs, "Tyrannosaurus"): 0
//
//    Array.IndexOf(dinosaurs, "Tyrannosaurus", 3): 5
//
//    Array.IndexOf(dinosaurs, "Tyrannosaurus", 2, 2): -1
Public Class Example

    Public Shared Sub Main()

        Dim dinosaurs() As String = { "Tyrannosaurus", _
            "Amargasaurus", _
            "Mamenchisaurus", _
            "Brachiosaurus", _
            "Deinonychus", _
            "Tyrannosaurus", _
            "Compsognathus" }

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

        Console.WriteLine(vbLf & _
            "Array.IndexOf(dinosaurs, ""Tyrannosaurus""): {0}", _
            Array.IndexOf(dinosaurs, "Tyrannosaurus"))

        Console.WriteLine(vbLf & _
            "Array.IndexOf(dinosaurs, ""Tyrannosaurus"", 3): {0}", _
            Array.IndexOf(dinosaurs, "Tyrannosaurus", 3))

        Console.WriteLine(vbLf & _
            "Array.IndexOf(dinosaurs, ""Tyrannosaurus"", 2, 2): {0}", _
            Array.IndexOf(dinosaurs, "Tyrannosaurus", 2, 2))

    End Sub
End Class

' This code example produces the following output:
'
'Tyrannosaurus
'Amargasaurus
'Mamenchisaurus
'Brachiosaurus
'Deinonychus
'Tyrannosaurus
'Compsognathus
'
'Array.IndexOf(dinosaurs, "Tyrannosaurus"): 0
'
'Array.IndexOf(dinosaurs, "Tyrannosaurus", 3): 5
'
'Array.IndexOf(dinosaurs, "Tyrannosaurus", 2, 2): -1

Comentarios

Este método busca una matriz unidimensional desde el elemento al startIndex final de la matriz. Para determinar si value existe en array, el método realiza una comparación de igualdad llamando al T.Equals método en cada elemento. Esto significa que, si T invalida el Equals método , se llama a esa invalidación.

Si startIndex es igual a Length, el método devuelve -1. Si startIndex es mayor que Array.Length, el método produce un ArgumentOutOfRangeException.

Este método es una operación O(n), donde n es el número de elementos de startIndex hasta el final de array.

Consulte también

Se aplica a

IndexOf<T>(T[], T, Int32, Int32)

Busca el objeto especificado en un intervalo de elementos de una matriz unidimensional y devuelve el índice de su primera aparición. El intervalo se extiende desde un índice especificado durante un número especificado de elementos.

public:
generic <typename T>
 static int IndexOf(cli::array <T> ^ array, T value, int startIndex, int count);
public static int IndexOf<T> (T[] array, T value, int startIndex, int count);
static member IndexOf : 'T[] * 'T * int * int -> int
Public Shared Function IndexOf(Of T) (array As T(), value As T, startIndex As Integer, count As Integer) As Integer

Parámetros de tipo

T

Tipo de los elementos de la matriz.

Parámetros

array
T[]

Matriz unidimensional de base cero en la que se va a buscar.

value
T

Objeto que se va a buscar en array.

startIndex
Int32

Índice inicial de base cero de la búsqueda. 0 (cero) es válido en una matriz vacía.

count
Int32

Número de elementos de la sección en la que se va a realizar la búsqueda.

Devoluciones

Índice de base cero de la primera aparición de value dentro del intervalo de elementos de array que comienza en startIndex y contiene el número de elementos especificados en count, si se encuentra; de lo contrario, -1.

Excepciones

array es null.

startIndex está fuera del intervalo de índices válidos para la array.

o bien

count es menor que cero.

o bien

startIndex y count no especifican una sección válida en array.

Ejemplos

En el ejemplo siguiente se muestran las tres sobrecargas genéricas del IndexOf método . Se crea una matriz de cadenas, con una entrada que aparece dos veces, en la ubicación del índice 0 y la ubicación del índice 5. La IndexOf<T>(T[], T) sobrecarga del método busca en la matriz desde el principio y busca la primera aparición de la cadena. La IndexOf<T>(T[], T, Int32) sobrecarga del método se usa para buscar en la matriz a partir de la ubicación de índice 3 y continuar hasta el final de la matriz y busca la segunda aparición de la cadena. Por último, la sobrecarga del IndexOf<T>(T[], T, Int32, Int32) método se usa para buscar en un intervalo de dos entradas, comenzando en la ubicación de índice dos; devuelve -1 porque no hay instancias de la cadena de búsqueda en ese intervalo.

using namespace System;

void main()
{
    array<String^>^ dinosaurs = { "Tyrannosaurus", 
        "Amargasaurus",
        "Mamenchisaurus",
        "Brachiosaurus",
        "Deinonychus",
        "Tyrannosaurus",
        "Compsognathus" };

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

    Console::WriteLine("\nArray.IndexOf(dinosaurs, \"Tyrannosaurus\"): {0}", 
        Array::IndexOf(dinosaurs, "Tyrannosaurus"));

    Console::WriteLine("\nArray.IndexOf(dinosaurs, \"Tyrannosaurus\", 3): {0}", 
        Array::IndexOf(dinosaurs, "Tyrannosaurus", 3));

    Console::WriteLine("\nArray.IndexOf(dinosaurs, \"Tyrannosaurus\", 2, 2): {0}", 
        Array::IndexOf(dinosaurs, "Tyrannosaurus", 2, 2));
}

/* This code example produces the following output:

Tyrannosaurus
Amargasaurus
Mamenchisaurus
Brachiosaurus
Deinonychus
Tyrannosaurus
Compsognathus

Array.IndexOf(dinosaurs, "Tyrannosaurus"): 0

Array.IndexOf(dinosaurs, "Tyrannosaurus", 3): 5

Array.IndexOf(dinosaurs, "Tyrannosaurus", 2, 2): -1
 */
string[] dinosaurs = { "Tyrannosaurus",
    "Amargasaurus",
    "Mamenchisaurus",
    "Brachiosaurus",
    "Deinonychus",
    "Tyrannosaurus",
    "Compsognathus" };

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

Console.WriteLine(
    "\nArray.IndexOf(dinosaurs, \"Tyrannosaurus\"): {0}",
    Array.IndexOf(dinosaurs, "Tyrannosaurus"));

Console.WriteLine(
    "\nArray.IndexOf(dinosaurs, \"Tyrannosaurus\", 3): {0}",
    Array.IndexOf(dinosaurs, "Tyrannosaurus", 3));

Console.WriteLine(
    "\nArray.IndexOf(dinosaurs, \"Tyrannosaurus\", 2, 2): {0}",
    Array.IndexOf(dinosaurs, "Tyrannosaurus", 2, 2));

/* This code example produces the following output:

Tyrannosaurus
Amargasaurus
Mamenchisaurus
Brachiosaurus
Deinonychus
Tyrannosaurus
Compsognathus

Array.IndexOf(dinosaurs, "Tyrannosaurus"): 0

Array.IndexOf(dinosaurs, "Tyrannosaurus", 3): 5

Array.IndexOf(dinosaurs, "Tyrannosaurus", 2, 2): -1
*/
open System

let dinosaurs =
    [| "Tyrannosaurus"
       "Amargasaurus"
       "Mamenchisaurus"
       "Brachiosaurus"
       "Deinonychus"
       "Tyrannosaurus"
       "Compsognathus" |]

printfn ""
for dino in dinosaurs do
    printfn $"{dino}"

Array.IndexOf(dinosaurs, "Tyrannosaurus")
|> printfn "\nArray.IndexOf(dinosaurs, \"Tyrannosaurus\"): %i"

Array.IndexOf(dinosaurs, "Tyrannosaurus", 3)
|> printfn "\nArray.IndexOf(dinosaurs, \"Tyrannosaurus\", 3): %i"

Array.IndexOf(dinosaurs, "Tyrannosaurus", 2, 2)
|> printfn "\nArray.IndexOf(dinosaurs, \"Tyrannosaurus\", 2, 2): %i"

// This code example produces the following output:
//
//    Tyrannosaurus
//    Amargasaurus
//    Mamenchisaurus
//    Brachiosaurus
//    Deinonychus
//    Tyrannosaurus
//    Compsognathus
//    
//    Array.IndexOf(dinosaurs, "Tyrannosaurus"): 0
//
//    Array.IndexOf(dinosaurs, "Tyrannosaurus", 3): 5
//
//    Array.IndexOf(dinosaurs, "Tyrannosaurus", 2, 2): -1
Public Class Example

    Public Shared Sub Main()

        Dim dinosaurs() As String = { "Tyrannosaurus", _
            "Amargasaurus", _
            "Mamenchisaurus", _
            "Brachiosaurus", _
            "Deinonychus", _
            "Tyrannosaurus", _
            "Compsognathus" }

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

        Console.WriteLine(vbLf & _
            "Array.IndexOf(dinosaurs, ""Tyrannosaurus""): {0}", _
            Array.IndexOf(dinosaurs, "Tyrannosaurus"))

        Console.WriteLine(vbLf & _
            "Array.IndexOf(dinosaurs, ""Tyrannosaurus"", 3): {0}", _
            Array.IndexOf(dinosaurs, "Tyrannosaurus", 3))

        Console.WriteLine(vbLf & _
            "Array.IndexOf(dinosaurs, ""Tyrannosaurus"", 2, 2): {0}", _
            Array.IndexOf(dinosaurs, "Tyrannosaurus", 2, 2))

    End Sub
End Class

' This code example produces the following output:
'
'Tyrannosaurus
'Amargasaurus
'Mamenchisaurus
'Brachiosaurus
'Deinonychus
'Tyrannosaurus
'Compsognathus
'
'Array.IndexOf(dinosaurs, "Tyrannosaurus"): 0
'
'Array.IndexOf(dinosaurs, "Tyrannosaurus", 3): 5
'
'Array.IndexOf(dinosaurs, "Tyrannosaurus", 2, 2): -1

Comentarios

Este método busca en los elementos de una matriz unidimensional de startIndex a startIndex más count menos 1, si count es mayor que 0. Para determinar si value existe en array, el método realiza una comparación de igualdad llamando al T.Equals método en cada elemento. Esto significa que, si T invalida el Equals método , se llama a esa invalidación.

Si startIndex es igual a Array.Length, el método devuelve -1. Si startIndex es mayor que Array.Length, el método produce un ArgumentOutOfRangeException.

Este método es una operación O(n), donde n es count.

Consulte también

Se aplica a

IndexOf<T>(T[], T)

Busca el objeto especificado y devuelve el índice de su primera aparición en una matriz unidimensional.

public:
generic <typename T>
 static int IndexOf(cli::array <T> ^ array, T value);
public static int IndexOf<T> (T[] array, T value);
static member IndexOf : 'T[] * 'T -> int
Public Shared Function IndexOf(Of T) (array As T(), value As T) As Integer

Parámetros de tipo

T

Tipo de los elementos de la matriz.

Parámetros

array
T[]

Matriz unidimensional de base cero en la que se va a buscar.

value
T

Objeto que se va a buscar en array.

Devoluciones

Índice de base cero de la primera aparición de value en la totalidad de array, si se encuentra; en caso contrario, -1.

Excepciones

array es null.

Ejemplos

En el ejemplo siguiente se muestran las tres sobrecargas genéricas del IndexOf método . Se crea una matriz de cadenas, con una entrada que aparece dos veces, en la ubicación del índice 0 y la ubicación del índice 5. La IndexOf<T>(T[], T) sobrecarga del método busca en la matriz desde el principio y busca la primera aparición de la cadena. La IndexOf<T>(T[], T, Int32) sobrecarga del método se usa para buscar en la matriz a partir de la ubicación de índice 3 y continuar hasta el final de la matriz y busca la segunda aparición de la cadena. Por último, la sobrecarga del IndexOf<T>(T[], T, Int32, Int32) método se usa para buscar en un intervalo de dos entradas, comenzando en la ubicación de índice dos; devuelve -1 porque no hay instancias de la cadena de búsqueda en ese intervalo.

using namespace System;

void main()
{
    array<String^>^ dinosaurs = { "Tyrannosaurus", 
        "Amargasaurus",
        "Mamenchisaurus",
        "Brachiosaurus",
        "Deinonychus",
        "Tyrannosaurus",
        "Compsognathus" };

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

    Console::WriteLine("\nArray.IndexOf(dinosaurs, \"Tyrannosaurus\"): {0}", 
        Array::IndexOf(dinosaurs, "Tyrannosaurus"));

    Console::WriteLine("\nArray.IndexOf(dinosaurs, \"Tyrannosaurus\", 3): {0}", 
        Array::IndexOf(dinosaurs, "Tyrannosaurus", 3));

    Console::WriteLine("\nArray.IndexOf(dinosaurs, \"Tyrannosaurus\", 2, 2): {0}", 
        Array::IndexOf(dinosaurs, "Tyrannosaurus", 2, 2));
}

/* This code example produces the following output:

Tyrannosaurus
Amargasaurus
Mamenchisaurus
Brachiosaurus
Deinonychus
Tyrannosaurus
Compsognathus

Array.IndexOf(dinosaurs, "Tyrannosaurus"): 0

Array.IndexOf(dinosaurs, "Tyrannosaurus", 3): 5

Array.IndexOf(dinosaurs, "Tyrannosaurus", 2, 2): -1
 */
string[] dinosaurs = { "Tyrannosaurus",
    "Amargasaurus",
    "Mamenchisaurus",
    "Brachiosaurus",
    "Deinonychus",
    "Tyrannosaurus",
    "Compsognathus" };

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

Console.WriteLine(
    "\nArray.IndexOf(dinosaurs, \"Tyrannosaurus\"): {0}",
    Array.IndexOf(dinosaurs, "Tyrannosaurus"));

Console.WriteLine(
    "\nArray.IndexOf(dinosaurs, \"Tyrannosaurus\", 3): {0}",
    Array.IndexOf(dinosaurs, "Tyrannosaurus", 3));

Console.WriteLine(
    "\nArray.IndexOf(dinosaurs, \"Tyrannosaurus\", 2, 2): {0}",
    Array.IndexOf(dinosaurs, "Tyrannosaurus", 2, 2));

/* This code example produces the following output:

Tyrannosaurus
Amargasaurus
Mamenchisaurus
Brachiosaurus
Deinonychus
Tyrannosaurus
Compsognathus

Array.IndexOf(dinosaurs, "Tyrannosaurus"): 0

Array.IndexOf(dinosaurs, "Tyrannosaurus", 3): 5

Array.IndexOf(dinosaurs, "Tyrannosaurus", 2, 2): -1
*/
open System

let dinosaurs =
    [| "Tyrannosaurus"
       "Amargasaurus"
       "Mamenchisaurus"
       "Brachiosaurus"
       "Deinonychus"
       "Tyrannosaurus"
       "Compsognathus" |]

printfn ""
for dino in dinosaurs do
    printfn $"{dino}"

Array.IndexOf(dinosaurs, "Tyrannosaurus")
|> printfn "\nArray.IndexOf(dinosaurs, \"Tyrannosaurus\"): %i"

Array.IndexOf(dinosaurs, "Tyrannosaurus", 3)
|> printfn "\nArray.IndexOf(dinosaurs, \"Tyrannosaurus\", 3): %i"

Array.IndexOf(dinosaurs, "Tyrannosaurus", 2, 2)
|> printfn "\nArray.IndexOf(dinosaurs, \"Tyrannosaurus\", 2, 2): %i"

// This code example produces the following output:
//
//    Tyrannosaurus
//    Amargasaurus
//    Mamenchisaurus
//    Brachiosaurus
//    Deinonychus
//    Tyrannosaurus
//    Compsognathus
//    
//    Array.IndexOf(dinosaurs, "Tyrannosaurus"): 0
//
//    Array.IndexOf(dinosaurs, "Tyrannosaurus", 3): 5
//
//    Array.IndexOf(dinosaurs, "Tyrannosaurus", 2, 2): -1
Public Class Example

    Public Shared Sub Main()

        Dim dinosaurs() As String = { "Tyrannosaurus", _
            "Amargasaurus", _
            "Mamenchisaurus", _
            "Brachiosaurus", _
            "Deinonychus", _
            "Tyrannosaurus", _
            "Compsognathus" }

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

        Console.WriteLine(vbLf & _
            "Array.IndexOf(dinosaurs, ""Tyrannosaurus""): {0}", _
            Array.IndexOf(dinosaurs, "Tyrannosaurus"))

        Console.WriteLine(vbLf & _
            "Array.IndexOf(dinosaurs, ""Tyrannosaurus"", 3): {0}", _
            Array.IndexOf(dinosaurs, "Tyrannosaurus", 3))

        Console.WriteLine(vbLf & _
            "Array.IndexOf(dinosaurs, ""Tyrannosaurus"", 2, 2): {0}", _
            Array.IndexOf(dinosaurs, "Tyrannosaurus", 2, 2))

    End Sub
End Class

' This code example produces the following output:
'
'Tyrannosaurus
'Amargasaurus
'Mamenchisaurus
'Brachiosaurus
'Deinonychus
'Tyrannosaurus
'Compsognathus
'
'Array.IndexOf(dinosaurs, "Tyrannosaurus"): 0
'
'Array.IndexOf(dinosaurs, "Tyrannosaurus", 3): 5
'
'Array.IndexOf(dinosaurs, "Tyrannosaurus", 2, 2): -1

Comentarios

Este método busca en todos los elementos de una matriz valueunidimensional . Para determinar si value existe en array, el método realiza una comparación de igualdad llamando al T.Equals método en cada elemento. Esto significa que, si T invalida el Equals método , se llama a esa invalidación.

Este método es una operación O(n), donde n es de Lengtharray.

Consulte también

Se aplica a