Esta documentación está archivada y no tiene mantenimiento.

Array.IndexOf (Método) (Array, Object, Int32, Int32)

Actualización: noviembre 2007

Busca el objeto especificado y devuelve el índice de la primera aparición en el intervalo de elementos de la matriz Array unidimensional que empieza en el índice especificado y contiene el número de elementos especificado.

Espacio de nombres:  System
Ensamblado:  mscorlib (en mscorlib.dll)

public static int IndexOf(
	Array array,
	Object value,
	int startIndex,
	int count
)
public static int IndexOf(
	Array array,
	Object value,
	int startIndex,
	int count
)
public static function IndexOf(
	array : Array, 
	value : Object, 
	startIndex : int, 
	count : int
) : int

Parámetros

array
Tipo: System.Array
Array unidimensional en la que se va a buscar.
value
Tipo: System.Object
Objeto que se va a buscar en array.
startIndex
Tipo: System.Int32
Índice inicial de la búsqueda.
count
Tipo: System.Int32
Número de elementos de la sección en la que se va a realizar la búsqueda.

Valor devuelto

Tipo: System.Int32
Índice de la primera aparición de value en el intervalo de elementos de array que comienza en startIndex y que contiene el número de elementos especificado en count, si se encuentra; en caso contrario, límite inferior de la matriz menos uno.

ExcepciónCondición
ArgumentNullException

array es null.

ArgumentOutOfRangeException

startIndex se encuentra fuera del intervalo de índices válidos para array.

O bien,

count es menor que cero.

O bien,

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

RankException

array es multidimensional.

La búsqueda en la matriz Array unidimensional se realiza hacia delante, comenzando en startIndex y terminando en startIndex más count menos 1, si count es mayor que 0.

Los elementos se comparan con el valor especificado, utilizando el método Object.Equals. Si el elemento es de tipo no intrínseco (definido por el usuario), se utiliza la implementación Equals de dicho tipo.

Como la mayoría de las matrices tienen un límite inferior igual a cero, este método normalmente devuelve -1 cuando no se encuentra value. En el caso excepcional de que el límite inferior de la matriz sea igual que Int32.MinValue y no se encuentre value, este método devuelve Int32.MaxValue, que es System.Int32.MinValue - 1.

Al pasar la propiedad Length de la matriz como startindex se devuelve el valor -1, mientras que los valores mayores que Length producen una excepción ArgumentOutOfRangeException.

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

En .NET Framework versión 2.0, este método utiliza los métodos Equals y CompareTo de Array para determinar si el objeto Object especificado por el parámetro value existe. En las versiones anteriores de .NET Framework, esta determinación se realizó utilizando los métodos Equals y CompareTo del propio objeto Object de value.

En el siguiente ejemplo de código se muestra la forma de determinar el índice de la primera aparición de un elemento especificado.

using System;
public class SamplesArray  {

   public static void Main()  {

      // Creates and initializes a new Array with three elements of the same value.
      Array myArray=Array.CreateInstance( typeof(String), 12 );
      myArray.SetValue( "the", 0 );
      myArray.SetValue( "quick", 1 );
      myArray.SetValue( "brown", 2 );
      myArray.SetValue( "fox", 3 );
      myArray.SetValue( "jumps", 4 );
      myArray.SetValue( "over", 5 );
      myArray.SetValue( "the", 6 );
      myArray.SetValue( "lazy", 7 );
      myArray.SetValue( "dog", 8 );
      myArray.SetValue( "in", 9 );
      myArray.SetValue( "the", 10 );
      myArray.SetValue( "barn", 11 );

      // Displays the values of the Array.
      Console.WriteLine( "The Array contains the following values:" );
      PrintIndexAndValues( myArray );

      // Searches for the first occurrence of the duplicated value.
      String myString = "the";
      int myIndex = Array.IndexOf( myArray, myString );
      Console.WriteLine( "The first occurrence of \"{0}\" is at index {1}.", myString, myIndex );

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

      // Searches for the first occurrence of the duplicated value in a section of the Array.
      myIndex = Array.IndexOf( myArray, myString, 6, 5 );
      Console.WriteLine( "The first occurrence of \"{0}\" between index 6 and index 10 is at index {1}.", myString, myIndex );
   }


   public static void PrintIndexAndValues( Array myArray )  {
      for ( int i = myArray.GetLowerBound(0); i <= myArray.GetUpperBound(0); i++ )
         Console.WriteLine( "\t[{0}]:\t{1}", i, myArray.GetValue( i ) );
   }
}
/*
This code produces 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 6 and index 10 is at index 6.
*/


import System.*;

public class SamplesArray
{
    public static void main(String[] args)
    {
        // Creates and initializes a new Array with three elements of the 
        // same value.
        Array myArray = Array.CreateInstance(String.class.ToType(), 12);
        myArray.SetValue("the", 0);
        myArray.SetValue("quick", 1);
        myArray.SetValue("brown", 2);
        myArray.SetValue("fox", 3);
        myArray.SetValue("jumps", 4);
        myArray.SetValue("over", 5);
        myArray.SetValue("the", 6);
        myArray.SetValue("lazy", 7);
        myArray.SetValue("dog", 8);
        myArray.SetValue("in", 9);
        myArray.SetValue("the", 10);
        myArray.SetValue("barn", 11);
        // Displays the values of the Array.
        Console.WriteLine("The Array contains the following values:");
        PrintIndexAndValues(myArray);
        // Searches for the first occurrence of the duplicated value.
        String myString = "the";
        int myIndex = Array.IndexOf(myArray, myString);
        Console.WriteLine("The first occurrence of \"{0}\" is at index {1}.", 
            myString, (Int32)myIndex);
        // Searches for the first occurrence of the duplicated value in the
        // last section of the Array.
        myIndex = Array.IndexOf(myArray, myString, 4);
        Console.WriteLine("The first occurrence of \"{0}\" between index 4 and"
            + " the end is at index {1}.", myString,(Int32)myIndex);
        // Searches for the first occurrence of the duplicated value in a 
        // section of the Array.
        myIndex = Array.IndexOf(myArray, myString, 6, 5);
        Console.WriteLine("The first occurrence of \"{0}\" between index 6"
            + " and index 10 is at index {1}.", myString,(Int32)myIndex);
    } //main

    public static void PrintIndexAndValues(Array myArray)
    {
        for (int i = myArray.GetLowerBound(0); i <= myArray.
            GetUpperBound(0); i++) {
            Console.WriteLine("\t[{0}]:\t{1}",(Int32)i,myArray.GetValue(i));
        }
    } //PrintIndexAndValues
} //SamplesArray 

 /*
 This code produces 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 6 and index 10 is at index 6.
 */


import System;

// Creates and initializes a new Array with three elements of the same value.
var myArray : System.Array = System.Array.CreateInstance( System.String, 12 );
myArray.SetValue( "the", 0 );
myArray.SetValue( "quick", 1 );
myArray.SetValue( "brown", 2 );
myArray.SetValue( "fox", 3 );
myArray.SetValue( "jumped", 4 );
myArray.SetValue( "over", 5 );
myArray.SetValue( "the", 6 );
myArray.SetValue( "lazy", 7 );
myArray.SetValue( "dog", 8 );
myArray.SetValue( "in", 9 );
myArray.SetValue( "the", 10 );
myArray.SetValue( "barn", 11 );

// Displays the values of the Array.
Console.WriteLine( "The Array contains the following values:" );
PrintIndexAndValues( myArray );

// Searches for the first occurrence of the duplicated value.
var myString : String = "the";
var myIndex : int = System.Array.IndexOf( myArray, myString );
Console.WriteLine( "The first occurrence of \"{0}\" is at index {1}.", myString, myIndex );

// Searches for the first occurrence of the duplicated value in the last section of the Array.
myIndex = System.Array.IndexOf( myArray, myString, 4 );
Console.WriteLine( "The first occurrence of \"{0}\" between index 4 and the end is at index {1}.", myString, myIndex );

// Searches for the first occurrence of the duplicated value in a section of the Array.
myIndex = System.Array.IndexOf( myArray, myString, 6, 5 );
Console.WriteLine( "The first occurrence of \"{0}\" between index 6 and index 10 is at index {1}.", myString, myIndex );


function PrintIndexAndValues( myArray : System.Array  )  {
   for ( var i : int = myArray.GetLowerBound(0); i <= myArray.GetUpperBound(0); i++ )
      Console.WriteLine( "\t[{0}]:\t{1}", i, myArray.GetValue( i ) );
}

 /*
 This code produces the following output.

 The Array contains the following values:
     [0]:    the
     [1]:    quick
     [2]:    brown
     [3]:    fox
     [4]:    jumped
     [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 6 and index 10 is at index 6.
 */


Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98, Windows CE, Windows Mobile para Smartphone, Windows Mobile para Pocket PC, Xbox 360

.NET Framework y .NET Compact Framework no admiten todas las versiones de cada plataforma. Para obtener una lista de las versiones compatibles, vea Requisitos de sistema de .NET Framework.

.NET Framework

Compatible con: 3.5, 3.0, 2.0, 1.1, 1.0

.NET Compact Framework

Compatible con: 3.5, 2.0, 1.0

XNA Framework

Compatible con: 2.0, 1.0
Mostrar: