Array.IndexOf Array.IndexOf Array.IndexOf Array.IndexOf Method

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.Searches for the specified object and returns the index of its first occurrence in a one-dimensional array or in a range of elements in the array.

Sobrecargas

IndexOf(Array, Object) IndexOf(Array, Object) IndexOf(Array, Object)

Busca el objeto especificado y devuelve el índice de su primera aparición en una matriz unidimensional.Searches for the specified object and returns the index of its first occurrence in a one-dimensional array.

IndexOf(Array, Object, Int32) IndexOf(Array, Object, Int32) 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.Searches for the specified object in a range of elements of a one-dimensional array, and returns the index of its first occurrence. El intervalo abarca desde un índice especificado hasta el final de la matriz.The range extends from a specified index to the end of the array.

IndexOf(Array, Object, Int32, Int32) IndexOf(Array, Object, Int32, Int32) 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.Searches for the specified object in a range of elements of a one-dimensional array, and returns the index of ifs first occurrence. El intervalo se extiende desde un índice especificado durante un número especificado de elementos.The range extends from a specified index for a specified number of elements.

IndexOf<T>(T[], T, Int32, Int32) IndexOf<T>(T[], T, Int32, Int32) IndexOf<T>(T[], T, Int32, Int32) 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.Searches for the specified object in a range of elements of a one-dimensional array, and returns the index of its first occurrence. El intervalo se extiende desde un índice especificado durante un número especificado de elementos.The range extends from a specified index for a specified number of elements.

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

Busca el objeto especificado y devuelve el índice de su primera aparición en una matriz unidimensional.Searches for the specified object and returns the index of its first occurrence in a one-dimensional array.

IndexOf<T>(T[], T, Int32) IndexOf<T>(T[], T, Int32) IndexOf<T>(T[], T, Int32) 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.Searches for the specified object in a range of elements of a one dimensional array, and returns the index of its first occurrence. El intervalo abarca desde un índice especificado hasta el final de la matriz.The range extends from a specified index to the end of the array.

IndexOf(Array, Object) IndexOf(Array, Object) IndexOf(Array, Object)

Busca el objeto especificado y devuelve el índice de su primera aparición en una matriz unidimensional.Searches for the specified object and returns the index of its first occurrence in a one-dimensional array.

public:
 static int IndexOf(Array ^ array, System::Object ^ value);
public static int IndexOf (Array array, object value);
static member IndexOf : Array * obj -> int

Parámetros

array
Array Array Array Array

Matriz unidimensional en la que se va a buscar.The one-dimensional array to search.

value
Object Object Object Object

Objeto que se va a buscar en array.The object to locate in 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.The index of the first occurrence of value in array, if found; otherwise, the lower bound of the array minus 1.

Excepciones

array es multidimensional.array is multidimensional.

Ejemplos

El ejemplo llama a las tres siguientes sobrecargas de los IndexOf método para encontrar el índice de una cadena en una matriz de cadenas:The example calls the following three overloads of the IndexOf method to find the index of a string in a string array:

  • IndexOf(Array, Object), para determinar la primera aparición de la cadena "the" en una matriz de cadenas.IndexOf(Array, Object), to determine the first occurrence of the string "the" in a string array.

  • IndexOf(Array, Object, Int32), para determinar la primera aparición de la cadena "the" en la cuarta a los últimos elementos de una matriz de cadenas.IndexOf(Array, Object, Int32), to determine the first occurrence of the string "the" in the fourth to the last elements of a string array.

  • IndexOf(Array, Object, Int32, Int32), para determinar la primera aparición de la cadena "the" en una cadena de matriz del elemento que sigue a la última coincidencia encontrada hasta el final de la matriz.IndexOf(Array, Object, Int32, Int32), to determine the first occurrence of the string "the" in a string array from the element that follows the last successful match to the end of the array.

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.
using System;

public class Example
{
    public static void Main()
    {
       // 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 unidimensional value.This method searches all the elements of a one-dimensional array for value. Para determinar si value existe en array, el método realiza una comparación de igualdad mediante una llamada a cada elemento Equals método hasta que encuentra una coincidencia.To determine whether value exists in array, the method performs an equality comparison by calling each element's Equals method until it finds a match. Esto significa que si el elemento invalida la Object.Equals(Object) , esa invalidación se llama al método.This means that if the element overrides the Object.Equals(Object) method, that override is called.

Dado que la mayoría de las matrices tienen un límite inferior de cero, este método devuelve -1 general sivalue no se encuentra.Because most arrays have a lower bound of zero, this method generally returns -1 ifvalue isn't found. En el extraño caso de que el límite inferior de la matriz es igual a Int32.MinValue(0 x 80000000) y value no se encuentra, este método devuelve Int32.MaxValue (0x7FFFFFFF).In the rare case that the lower bound of the array is equal to Int32.MinValue(0x80000000) and value isn't found, this method returns Int32.MaxValue (0x7FFFFFFF).

Este método es O (n) operación, donde n es el Length de array.This method is an O(n) operation, where n is the Length of array.

Consulte también:

IndexOf(Array, Object, Int32) IndexOf(Array, Object, Int32) 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.Searches for the specified object in a range of elements of a one-dimensional array, and returns the index of its first occurrence. El intervalo abarca desde un índice especificado hasta el final de la matriz.The range extends from a specified index to the end of the array.

public:
 static int IndexOf(Array ^ array, System::Object ^ value, int startIndex);
public static int IndexOf (Array array, object value, int startIndex);
static member IndexOf : Array * obj * int -> int

Parámetros

array
Array Array Array Array

Matriz unidimensional en la que se va a buscar.The one-dimensional array to search.

value
Object Object Object Object

Objeto que se va a buscar en array.The object to locate in array.

startIndex
Int32 Int32 Int32 Int32

Índice inicial de la búsqueda.The starting index of the search. 0 (cero) es válido en una matriz vacía.0 (zero) is valid in an empty array.

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.The index of the first occurrence of value, if it's found, within the range of elements in array that extends from startIndex to the last element; otherwise, the lower bound of the array minus 1.

Excepciones

startIndex está fuera del intervalo de índices válidos para array.startIndex is outside the range of valid indexes for array.

array es multidimensional.array is multidimensional.

Ejemplos

El ejemplo llama a las tres siguientes sobrecargas de los IndexOf método para encontrar el índice de una cadena en una matriz de cadenas:The example calls the following three overloads of the IndexOf method to find the index of a string in a string array:

  • IndexOf(Array, Object), para determinar la primera aparición de la cadena "the" en una matriz de cadenas.IndexOf(Array, Object), to determine the first occurrence of the string "the" in a string array.

  • IndexOf(Array, Object, Int32), para determinar la primera aparición de la cadena "the" en la cuarta a los últimos elementos de una matriz de cadenas.IndexOf(Array, Object, Int32), to determine the first occurrence of the string "the" in the fourth to the last elements of a string array.

  • IndexOf(Array, Object, Int32, Int32), para determinar la primera aparición de la cadena "the" en una cadena de matriz del elemento que sigue a la última coincidencia encontrada hasta el final de la matriz.IndexOf(Array, Object, Int32, Int32), to determine the first occurrence of the string "the" in a string array from the element that follows the last successful match to the end of the array.

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.
using System;

public class Example
{
    public static void Main()
    {
       // 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 una matriz unidimensional del elemento en el índice startIndex hasta el último elemento.This method searches a one-dimensional array from the element at index startIndex to the last element. Para determinar si value existe en array, el método realiza una comparación de igualdad mediante una llamada a la Equals método de todos los elementos hasta que encuentra una coincidencia.To determine whether value exists in array, the method performs an equality comparison by calling the Equals method of every element until it finds a match. Esto significa que si el elemento invalida la Object.Equals(Object) , esa invalidación se llama al método.This means that if the element overrides the Object.Equals(Object) method, that override is called.

Dado que la mayoría de las matrices tienen un límite inferior de cero, este método devuelve -1 general si value no se encuentra.Because most arrays have a lower bound of zero, this method generally returns -1 if value isn't found. En el extraño caso de que el límite inferior de la matriz es igual a Int32.MinValue(0 x 80000000) y value no se encuentra, este método devuelve Int32.MaxValue (0x7FFFFFFF).In the rare case that the lower bound of the array is equal to Int32.MinValue(0x80000000) and value isn't found, this method returns Int32.MaxValue (0x7FFFFFFF).

Si startIndex es igual a Array.Length, el método devuelve -1.If startIndex equals Array.Length,the method returns -1. Si startIndex es mayor que Array.Length, el método produce una ArgumentOutOfRangeException.If startIndex is greater than Array.Length, the method throws an ArgumentOutOfRangeException.

Este método es O (n) operación, donde n es el número de elementos de startIndex al final de array.This method is an O(n) operation, where n is the number of elements from startIndex to the end of array.

Consulte también:

IndexOf(Array, Object, Int32, Int32) IndexOf(Array, Object, Int32, Int32) 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.Searches for the specified object in a range of elements of a one-dimensional array, and returns the index of ifs first occurrence. El intervalo se extiende desde un índice especificado durante un número especificado de elementos.The range extends from a specified index for a specified number of elements.

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);
static member IndexOf : Array * obj * int * int -> int

Parámetros

array
Array Array Array Array

Matriz unidimensional en la que se va a buscar.The one-dimensional array to search.

value
Object Object Object Object

Objeto que se va a buscar en array.The object to locate in array.

startIndex
Int32 Int32 Int32 Int32

Índice inicial de la búsqueda.The starting index of the search. 0 (cero) es válido en una matriz vacía.0 (zero) is valid in an empty array.

count
Int32 Int32 Int32 Int32

Número de elementos que se van a buscar.The number of elements to search.

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.The index of the first occurrence of value, if it's found in the array from index startIndex to startIndex + count - 1; otherwise, the lower bound of the array minus 1.

Excepciones

startIndex está fuera del intervalo de índices válidos para la array.startIndex is outside the range of valid indexes for array.

-o bien--or- count es menor que cero.count is less than zero.

-o bien--or- startIndex y count no especifican una sección válida en array.startIndex and count do not specify a valid section in array.

array es multidimensional.array is multidimensional.

Ejemplos

El ejemplo llama a las tres siguientes sobrecargas de los IndexOf método para encontrar el índice de una cadena en una matriz de cadenas:The example calls the following three overloads of the IndexOf method to find the index of a string in a string array:

  • IndexOf(Array, Object), para determinar la primera aparición de la cadena "the" en una matriz de cadenas.IndexOf(Array, Object), to determine the first occurrence of the string "the" in a string array.

  • IndexOf(Array, Object, Int32), para determinar la primera aparición de la cadena "the" en la cuarta a los últimos elementos de una matriz de cadenas.IndexOf(Array, Object, Int32), to determine the first occurrence of the string "the" in the fourth to the last elements of a string array.

  • IndexOf(Array, Object, Int32, Int32), para determinar la primera aparición de la cadena "the" en una cadena de matriz del elemento que sigue a la última coincidencia encontrada hasta el final de la matriz.IndexOf(Array, Object, Int32, Int32), to determine the first occurrence of the string "the" in a string array from the element that follows the last successful match to the end of the array. Para determinar el valor de la count argumento, se resta el límite superior de la matriz desde el índice de inicio y agrega uno.To determine the value of the count argument, it subtracts the upper bound of the array from the starting index and adds one.

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.
using System;

public class Example
{
    public static void Main()
    {
       // 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 los elementos de una matriz unidimensional de startIndex a startIndex plus count menos 1, si count es mayor que 0.This method searches the elements of a one-dimensional array from startIndex to startIndex plus count minus 1, if count is greater than 0. Para determinar si value existe en array, el método realiza una comparación de igualdad mediante una llamada a la Equals método de todos los elementos hasta que encuentra una coincidencia.To determine whether value exists in array, the method performs an equality comparison by calling the Equals method of every element until it finds a match. Esto significa que si el elemento invalida la Object.Equals , esa invalidación se llama al método.This means that if the element overrides the Object.Equals method, that override is called.

Dado que la mayoría de las matrices tienen un límite inferior de cero, este método normalmente devuelve-1 cuando value no se encuentra.Because most arrays have a lower bound of zero, this method generally returns -1 when value isn't found. En el extraño caso de que el límite inferior de la matriz es igual a Int32.MinValue (0 x 80000000) y value no se encuentra, este método devuelve Int32.MaxValue (0x7FFFFFFF).In the rare case that the lower bound of the array is equal to Int32.MinValue (0x80000000) and value isn't found, this method returns Int32.MaxValue (0x7FFFFFFF).

Si startindex es igual a Array.Length, el método devuelve -1.If startindex equals Array.Length, the method returns -1. Si startIndex es mayor que Array.Length, el método produce una ArgumentOutOfRangeException.If startIndex is greater than Array.Length, the method throws an ArgumentOutOfRangeException.

Este método es O (n) operación, donde n es count.This method is an O(n) operation, where n is count.

Consulte también:

IndexOf<T>(T[], T, Int32, Int32) IndexOf<T>(T[], T, Int32, Int32) IndexOf<T>(T[], T, Int32, Int32) 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.Searches for the specified object in a range of elements of a one-dimensional array, and returns the index of its first occurrence. El intervalo se extiende desde un índice especificado durante un número especificado de elementos.The range extends from a specified index for a specified number of elements.

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.The type of the elements of the array.

Parámetros

array
T[]

Matriz unidimensional de base cero en la que se va a buscar.The one-dimensional, zero-based array to search.

value
T T T T

Objeto que se va a buscar en array.The object to locate in array.

startIndex
Int32 Int32 Int32 Int32

Índice inicial de base cero de la búsqueda.The zero-based starting index of the search. 0 (cero) es válido en una matriz vacía.0 (zero) is valid in an empty array.

count
Int32 Int32 Int32 Int32

Número de elementos de la sección en la que se va a realizar la búsqueda.The number of elements in the section to search.

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.The zero-based index of the first occurrence of value within the range of elements in array that starts at startIndex and contains the number of elements specified in count, if found; otherwise, -1.

Excepciones

startIndex está fuera del intervalo de índices válidos para la array.startIndex is outside the range of valid indexes for array.

-o bien--or- count es menor que cero.count is less than zero.

-o bien--or- startIndex y count no especifican una sección válida en array.startIndex and count do not specify a valid section in array.

Ejemplos

El ejemplo siguiente muestra tres sobrecargas genéricas de los IndexOf método.The following example demonstrates all three generic overloads of the IndexOf method. Se crea una matriz de cadenas, con una entrada que aparece dos veces, en la ubicación de índice 0 y la ubicación de índice 5.An array of strings is created, with one entry that appears twice, at index location 0 and index location 5. El IndexOf<T>(T[], T) sobrecarga del método busca en la matriz desde el principio y busca la primera aparición de la cadena.The IndexOf<T>(T[], T) method overload searches the array from the beginning, and finds the first occurrence of the string. El IndexOf<T>(T[], T, Int32) sobrecarga del método se utiliza para buscar el principio de la matriz en la posición de índice 3 y continuando hasta el final de la matriz y encuentra la segunda aparición de la cadena.The IndexOf<T>(T[], T, Int32) method overload is used to search the array beginning with index location 3 and continuing to the end of the array, and finds the second occurrence of the string. Por último, el IndexOf<T>(T[], T, Int32, Int32) sobrecarga del método se utiliza para buscar un intervalo de dos entradas, comenzando en la posición de índice dos; devuelve -1 porque no hay ninguna instancia de la cadena de búsqueda en ese intervalo.Finally, the IndexOf<T>(T[], T, Int32, Int32) method overload is used to search a range of two entries, beginning at index location two; it returns -1 because there are no instances of the search string in that range.

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
 */
using System;

public class Example
{
    public static void Main()
    {
        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
 */
Imports System

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 plus count menos 1, si count es mayor que 0.This method searches the elements of a one-dimensional array from startIndex to startIndex plus count minus 1, if count is greater than 0. Para determinar si value existe en array, el método realiza una comparación de igualdad mediante una llamada a la T.Equals método en cada elemento.To determine whether value exists in array, the method performs an equality comparison by calling the T.Equals method on every element. Esto significa que si T invalida la Equals , esa invalidación se llama al método.This means that if T overrides the Equals method, that override is called.

Si startIndex es igual a Array.Length, el método devuelve -1.If startIndex equals Array.Length, the method returns -1. Si startIndex es mayor que Array.Length, el método produce una ArgumentOutOfRangeException.If startIndex is greater than Array.Length, the method throws an ArgumentOutOfRangeException.

Este método es O (n) operación, donde n es count.This method is an O(n) operation, where n is count.

Consulte también:

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

Busca el objeto especificado y devuelve el índice de su primera aparición en una matriz unidimensional.Searches for the specified object and returns the index of its first occurrence in a one-dimensional array.

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.The type of the elements of the array.

Parámetros

array
T[]

Matriz unidimensional de base cero en la que se va a buscar.The one-dimensional, zero-based array to search.

value
T T T T

Objeto que se va a buscar en array.The object to locate in 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.The zero-based index of the first occurrence of value in the entire array, if found; otherwise, -1.

Excepciones

Ejemplos

El ejemplo siguiente muestra tres sobrecargas genéricas de los IndexOf método.The following example demonstrates all three generic overloads of the IndexOf method. Se crea una matriz de cadenas, con una entrada que aparece dos veces, en la ubicación de índice 0 y la ubicación de índice 5.An array of strings is created, with one entry that appears twice, at index location 0 and index location 5. El IndexOf<T>(T[], T) sobrecarga del método busca en la matriz desde el principio y busca la primera aparición de la cadena.The IndexOf<T>(T[], T) method overload searches the array from the beginning, and finds the first occurrence of the string. El IndexOf<T>(T[], T, Int32) sobrecarga del método se utiliza para buscar el principio de la matriz en la posición de índice 3 y continuando hasta el final de la matriz y encuentra la segunda aparición de la cadena.The IndexOf<T>(T[], T, Int32) method overload is used to search the array beginning with index location 3 and continuing to the end of the array, and finds the second occurrence of the string. Por último, el IndexOf<T>(T[], T, Int32, Int32) sobrecarga del método se utiliza para buscar un intervalo de dos entradas, comenzando en la posición de índice dos; devuelve -1 porque no hay ninguna instancia de la cadena de búsqueda en ese intervalo.Finally, the IndexOf<T>(T[], T, Int32, Int32) method overload is used to search a range of two entries, beginning at index location two; it returns -1 because there are no instances of the search string in that range.

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
 */
using System;

public class Example
{
    public static void Main()
    {
        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
 */
Imports System

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 unidimensional value.This method searches all the elements of a one-dimensional array for value. Para determinar si value existe en array, el método realiza una comparación de igualdad mediante una llamada a la T.Equals método en cada elemento.To determine whether value exists in array, the method performs an equality comparison by calling the T.Equals method on every element. Esto significa que si T invalida la Equals , esa invalidación se llama al método.This means that if T overrides the Equals method, that override is called.

Este método es O (n) operación, donde n es el Length de array.This method is an O(n) operation, where n is the Length of array.

Consulte también:

IndexOf<T>(T[], T, Int32) IndexOf<T>(T[], T, Int32) IndexOf<T>(T[], T, Int32) 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.Searches for the specified object in a range of elements of a one dimensional array, and returns the index of its first occurrence. El intervalo abarca desde un índice especificado hasta el final de la matriz.The range extends from a specified index to the end of the array.

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.The type of the elements of the array.

Parámetros

array
T[]

Matriz unidimensional de base cero en la que se va a buscar.The one-dimensional, zero-based array to search.

value
T T T T

Objeto que se va a buscar en array.The object to locate in array.

startIndex
Int32 Int32 Int32 Int32

Índice inicial de base cero de la búsqueda.The zero-based starting index of the search. 0 (cero) es válido en una matriz vacía.0 (zero) is valid in an empty array.

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.The zero-based index of the first occurrence of value within the range of elements in array that extends from startIndex to the last element, if found; otherwise, -1.

Excepciones

startIndex está fuera del intervalo de índices válidos para la array.startIndex is outside the range of valid indexes for array.

Ejemplos

El ejemplo siguiente muestra tres sobrecargas genéricas de los IndexOf método.The following example demonstrates all three generic overloads of the IndexOf method. Se crea una matriz de cadenas, con una entrada que aparece dos veces, en la ubicación de índice 0 y la ubicación de índice 5.An array of strings is created, with one entry that appears twice, at index location 0 and index location 5. El IndexOf<T>(T[], T) sobrecarga del método busca en la matriz desde el principio y busca la primera aparición de la cadena.The IndexOf<T>(T[], T) method overload searches the array from the beginning, and finds the first occurrence of the string. El IndexOf<T>(T[], T, Int32) sobrecarga del método se utiliza para buscar el principio de la matriz en la posición de índice 3 y continuando hasta el final de la matriz y encuentra la segunda aparición de la cadena.The IndexOf<T>(T[], T, Int32) method overload is used to search the array beginning with index location 3 and continuing to the end of the array, and finds the second occurrence of the string. Por último, el IndexOf<T>(T[], T, Int32, Int32) sobrecarga del método se utiliza para buscar un intervalo de dos entradas, comenzando en la posición de índice dos; devuelve -1 porque no hay ninguna instancia de la cadena de búsqueda en ese intervalo.Finally, the IndexOf<T>(T[], T, Int32, Int32) method overload is used to search a range of two entries, beginning at index location two; it returns -1 because there are no instances of the search string in that range.

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
 */
using System;

public class Example
{
    public static void Main()
    {
        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
 */
Imports System

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 una matriz unidimensional del elemento en el startIndex al final de la matriz.This method searches a one-dimensional array from the element at startIndex to the end of the array. Para determinar si value existe en array, el método realiza una comparación de igualdad mediante una llamada a la T.Equals método en cada elemento.To determine whether value exists in array, the method performs an equality comparison by calling the T.Equals method on every element. Esto significa que si T invalida la Equals , esa invalidación se llama al método.This means that if T overrides the Equals method, that override is called.

Si startIndex es igual a Length, el método devuelve - 1.If startIndex es mayor que Array.Length, el método produce una ArgumentOutOfRangeException.If startIndex equals Length,the method returns -1.If startIndex is greater than Array.Length, the method throws an ArgumentOutOfRangeException.

Este método es O (n) operación, donde n es el número de elementos de startIndex al final de array.This method is an O(n) operation, where n is the number of elements from startIndex to the end of array.

Consulte también:

Se aplica a