Array.LastIndexOf Array.LastIndexOf Array.LastIndexOf Array.LastIndexOf Method

Definición

Devuelve el índice de la última aparición de un valor en una matriz Array unidimensional o en una parte de la matriz Array.Returns the index of the last occurrence of a value in a one-dimensional Array or in a portion of the Array.

Sobrecargas

LastIndexOf(Array, Object) LastIndexOf(Array, Object) LastIndexOf(Array, Object)

Busca el objeto especificado y devuelve el índice de la última aparición en toda la matriz Array unidimensional.Searches for the specified object and returns the index of the last occurrence within the entire one-dimensional Array.

LastIndexOf(Array, Object, Int32) LastIndexOf(Array, Object, Int32) LastIndexOf(Array, Object, Int32)

Busca el objeto especificado y devuelve el índice de la última aparición en el intervalo de elementos de la matriz Array unidimensional que se extiende desde el primer elemento hasta el índice especificado.Searches for the specified object and returns the index of the last occurrence within the range of elements in the one-dimensional Array that extends from the first element to the specified index.

LastIndexOf(Array, Object, Int32, Int32) LastIndexOf(Array, Object, Int32, Int32) LastIndexOf(Array, Object, Int32, Int32)

Busca el objeto especificado y devuelve el índice de la última aparición dentro del intervalo de elementos de la Array unidimensional que contiene el número especificado de elementos y termina en el índice especificado.Searches for the specified object and returns the index of the last occurrence within the range of elements in the one-dimensional Array that contains the specified number of elements and ends at the specified index.

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

Busca el objeto especificado y devuelve el índice de la última aparición de toda la Array.Searches for the specified object and returns the index of the last occurrence within the entire Array.

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

Busca el objeto especificado y devuelve el índice de la última aparición en el intervalo de elementos de la Array que se extiende desde el primer elemento hasta el índice especificado.Searches for the specified object and returns the index of the last occurrence within the range of elements in the Array that extends from the first element to the specified index.

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

Busca el objeto especificado y devuelve el índice de la última aparición en el intervalo de elementos de la Array que contiene el número de elementos especificado y termina en el índice especificado.Searches for the specified object and returns the index of the last occurrence within the range of elements in the Array that contains the specified number of elements and ends at the specified index.

LastIndexOf(Array, Object) LastIndexOf(Array, Object) LastIndexOf(Array, Object)

Busca el objeto especificado y devuelve el índice de la última aparición en toda la matriz Array unidimensional.Searches for the specified object and returns the index of the last occurrence within the entire one-dimensional Array.

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

Parámetros

array
Array Array Array Array

Array unidimensional 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 última aparición de value en toda la matriz array, si se encuentra; en caso contrario, límite inferior de la matriz menos 1.The index of the last occurrence of value within the entire array, if found; otherwise, the lower bound of the array minus 1.

Excepciones

array es multidimensional.array is multidimensional.

Ejemplos

En el ejemplo de código siguiente se muestra cómo determinar el índice de la última aparición de un elemento especificado en una matriz.The following code example shows how to determine the index of the last occurrence of a specified element in an array.

using namespace System;
void PrintIndexAndValues( Array^ myArray );

void main()
{
   // Creates and initializes a new Array instance with three elements of the same value.
   Array^ myArray = Array::CreateInstance( String::typeid, 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 instance contains the following values:" );
   PrintIndexAndValues( myArray );

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

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

   // Searches for the last occurrence of the duplicated value in a section of the Array.  
   // Note that the start index is greater than the end index because the search is done backward.
   myIndex = Array::LastIndexOf( myArray, myString, 10, 6 );
   Console::WriteLine(  "The last occurrence of \"{0}\" between index 5 and index 10 is at index {1}.", myString, myIndex );
}

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 instance 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 last occurrence of "the" is at index 10.
 The last occurrence of "the" between the start and index 8 is at index 6.
 The last occurrence of "the" between index 5 and index 10 is at index 10.
 */
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 last occurrence of the duplicated value.
      String myString = "the";
      int myIndex = Array.LastIndexOf( myArray, myString );
      Console.WriteLine( "The last occurrence of \"{0}\" is at index {1}.", myString, myIndex );

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

      // Searches for the last occurrence of the duplicated value in a section of the Array.
      // Note that the start index is greater than the end index because the search is done backward.
      myIndex = Array.LastIndexOf( myArray, myString, 10, 6 );
      Console.WriteLine( "The last occurrence of \"{0}\" between index 5 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 last occurrence of "the" is at index 10.
The last occurrence of "the" between the start and index 8 is at index 6.
The last occurrence of "the" between index 5 and index 10 is at index 10.
*/
Imports System
Imports Microsoft.VisualBasic

Public Class SamplesArray    
    
    Public Shared Sub Main()
        
        ' Creates and initializes a new Array with three elements of
        ' the same value.
        Dim myArray As Array = Array.CreateInstance(GetType(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 last occurrence of the duplicated value.
        Dim myString As String = "the"
        Dim myIndex As Integer = Array.LastIndexOf(myArray, myString)
        Console.WriteLine("The last occurrence of ""{0}"" is at index {1}.", _
           myString, myIndex)
        
        ' Searches for the last occurrence of the duplicated value in the first
        ' section of the Array.
        myIndex = Array.LastIndexOf(myArray, myString, 8)
        Console.WriteLine("The last occurrence of ""{0}"" between the start " _
           + "and index 8 is at index {1}.", myString, myIndex)
        
        ' Searches for the last occurrence of the duplicated value in a section
        ' of the Array.  Note that the start index is greater than the end
        ' index because the search is done backward.
        myIndex = Array.LastIndexOf(myArray, myString, 10, 6)
        Console.WriteLine("The last occurrence of ""{0}"" between index 5 " _
           + "and index 10 is at index {1}.", myString, myIndex)
    End Sub
    
    
    Public Shared Sub PrintIndexAndValues(myArray As Array)
        Dim i As Integer
        For i = myArray.GetLowerBound(0) To myArray.GetUpperBound(0)
            Console.WriteLine(ControlChars.Tab + "[{0}]:" + ControlChars.Tab _
               + "{1}", i, myArray.GetValue(i))
        Next i
    End Sub
End Class

' 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 last occurrence of "the" is at index 10.
' The last occurrence of "the" between the start and index 8 is at index 6.
' The last occurrence of "the" between index 5 and index 10 is at index 10. 

Comentarios

Unidimensional Array se realiza hacia atrás a partir del último elemento y terminando en el primer elemento.The one-dimensional Array is searched backward starting at the last element and ending at the first element.

Los elementos se comparan con el valor especificado mediante el Object.Equals método.The elements are compared to the specified value using the Object.Equals method. Si el tipo de elemento es un tipo no intrínseco (definido por el usuario), el Equals se utiliza la implementación de ese tipo.If the element type is a nonintrinsic (user-defined) type, the Equals implementation of that type is used.

Como la mayoría de las matrices tienen un límite inferior de cero, este método normalmente devuelve-1 cuando value no se encuentra.Since most arrays will have a lower bound of zero, this method would generally return -1 when value is not found. En el extraño caso de que el límite inferior de la matriz es igual a Int32.MinValue y value no se encuentra, este método devuelve Int32.MaxValue, que es System.Int32.MinValue - 1.In the rare case that the lower bound of the array is equal to Int32.MinValue and value is not found, this method returns Int32.MaxValue, which is System.Int32.MinValue - 1.

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.

En la versión 2.0 de .NET Framework, este método utiliza la Equals y CompareTo métodos de la Array para determinar si el Object especificado por el value parámetro existe.In the .NET Framework version 2.0, this method uses the Equals and CompareTo methods of the Array to determine whether the Object specified by the value parameter exists. En las versiones anteriores de .NET Framework, esta determinación se realiza mediante el uso de la Equals y CompareTo métodos de la value Object propio.In the earlier versions of the .NET Framework, this determination was made by using the Equals and CompareTo methods of the valueObject itself.

CompareTo métodos de la item parámetro en los objetos de la colección.CompareTo methods of the item parameter on the objects in the collection.

Consulte también:

LastIndexOf(Array, Object, Int32) LastIndexOf(Array, Object, Int32) LastIndexOf(Array, Object, Int32)

Busca el objeto especificado y devuelve el índice de la última aparición en el intervalo de elementos de la matriz Array unidimensional que se extiende desde el primer elemento hasta el índice especificado.Searches for the specified object and returns the index of the last occurrence within the range of elements in the one-dimensional Array that extends from the first element to the specified index.

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

Parámetros

array
Array Array Array Array

Array unidimensional 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 hacia atrás.The starting index of the backward search.

Devoluciones

Índice de la última aparición de value en el intervalo de elementos de array que se extiende desde el primer elemento hasta startIndex, si se encuentra; en caso contrario, límite inferior de la matriz menos 1.The index of the last occurrence of value within the range of elements in array that extends from the first element to startIndex, if found; 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

En el ejemplo de código siguiente se muestra cómo determinar el índice de la última aparición de un elemento especificado en una matriz.The following code example shows how to determine the index of the last occurrence of a specified element in an array.

using namespace System;
void PrintIndexAndValues( Array^ myArray );

void main()
{
   // Creates and initializes a new Array instance with three elements of the same value.
   Array^ myArray = Array::CreateInstance( String::typeid, 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 instance contains the following values:" );
   PrintIndexAndValues( myArray );

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

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

   // Searches for the last occurrence of the duplicated value in a section of the Array.  
   // Note that the start index is greater than the end index because the search is done backward.
   myIndex = Array::LastIndexOf( myArray, myString, 10, 6 );
   Console::WriteLine(  "The last occurrence of \"{0}\" between index 5 and index 10 is at index {1}.", myString, myIndex );
}

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 instance 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 last occurrence of "the" is at index 10.
 The last occurrence of "the" between the start and index 8 is at index 6.
 The last occurrence of "the" between index 5 and index 10 is at index 10.
 */
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 last occurrence of the duplicated value.
      String myString = "the";
      int myIndex = Array.LastIndexOf( myArray, myString );
      Console.WriteLine( "The last occurrence of \"{0}\" is at index {1}.", myString, myIndex );

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

      // Searches for the last occurrence of the duplicated value in a section of the Array.
      // Note that the start index is greater than the end index because the search is done backward.
      myIndex = Array.LastIndexOf( myArray, myString, 10, 6 );
      Console.WriteLine( "The last occurrence of \"{0}\" between index 5 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 last occurrence of "the" is at index 10.
The last occurrence of "the" between the start and index 8 is at index 6.
The last occurrence of "the" between index 5 and index 10 is at index 10.
*/
Imports System
Imports Microsoft.VisualBasic

Public Class SamplesArray    
    
    Public Shared Sub Main()
        
        ' Creates and initializes a new Array with three elements of
        ' the same value.
        Dim myArray As Array = Array.CreateInstance(GetType(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 last occurrence of the duplicated value.
        Dim myString As String = "the"
        Dim myIndex As Integer = Array.LastIndexOf(myArray, myString)
        Console.WriteLine("The last occurrence of ""{0}"" is at index {1}.", _
           myString, myIndex)
        
        ' Searches for the last occurrence of the duplicated value in the first
        ' section of the Array.
        myIndex = Array.LastIndexOf(myArray, myString, 8)
        Console.WriteLine("The last occurrence of ""{0}"" between the start " _
           + "and index 8 is at index {1}.", myString, myIndex)
        
        ' Searches for the last occurrence of the duplicated value in a section
        ' of the Array.  Note that the start index is greater than the end
        ' index because the search is done backward.
        myIndex = Array.LastIndexOf(myArray, myString, 10, 6)
        Console.WriteLine("The last occurrence of ""{0}"" between index 5 " _
           + "and index 10 is at index {1}.", myString, myIndex)
    End Sub
    
    
    Public Shared Sub PrintIndexAndValues(myArray As Array)
        Dim i As Integer
        For i = myArray.GetLowerBound(0) To myArray.GetUpperBound(0)
            Console.WriteLine(ControlChars.Tab + "[{0}]:" + ControlChars.Tab _
               + "{1}", i, myArray.GetValue(i))
        Next i
    End Sub
End Class

' 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 last occurrence of "the" is at index 10.
' The last occurrence of "the" between the start and index 8 is at index 6.
' The last occurrence of "the" between index 5 and index 10 is at index 10. 

Comentarios

Unidimensional Array es la búsqueda hacia atrás, empezando en startIndex y terminando en el primer elemento.The one-dimensional Array is searched backward starting at startIndex and ending at the first element.

Los elementos se comparan con el valor especificado mediante el Object.Equals método.The elements are compared to the specified value using the Object.Equals method. Si el tipo de elemento es un tipo no intrínseco (definido por el usuario), el Equals se utiliza la implementación de ese tipo.If the element type is a nonintrinsic (user-defined) type, the Equals implementation of that type is used.

Como la mayoría de las matrices tienen un límite inferior de cero, este método normalmente devuelve-1 cuando value no se encuentra.Since most arrays will have a lower bound of zero, this method would generally return -1 when value is not found. En el extraño caso de que el límite inferior de la matriz es igual a Int32.MinValue y value no se encuentra, este método devuelve Int32.MaxValue, que es System.Int32.MinValue - 1.In the rare case that the lower bound of the array is equal to Int32.MinValue and value is not found, this method returns Int32.MaxValue, which is System.Int32.MinValue - 1.

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

En la versión 2.0 de .NET Framework, este método utiliza la Equals y CompareTo métodos de la Array para determinar si el Object especificado por el value parámetro existe.In the .NET Framework version 2.0, this method uses the Equals and CompareTo methods of the Array to determine whether the Object specified by the value parameter exists. En las versiones anteriores de .NET Framework, esta determinación se realiza mediante el uso de la Equals y CompareTo métodos de la value Object propio.In the earlier versions of the .NET Framework, this determination was made by using the Equals and CompareTo methods of the valueObject itself.

Consulte también:

LastIndexOf(Array, Object, Int32, Int32) LastIndexOf(Array, Object, Int32, Int32) LastIndexOf(Array, Object, Int32, Int32)

Busca el objeto especificado y devuelve el índice de la última aparición dentro del intervalo de elementos de la Array unidimensional que contiene el número especificado de elementos y termina en el índice especificado.Searches for the specified object and returns the index of the last occurrence within the range of elements in the one-dimensional Array that contains the specified number of elements and ends at the specified index.

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

Parámetros

array
Array Array Array Array

Array unidimensional 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 hacia atrás.The starting index of the backward search.

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

El índice de la última aparición de value dentro del intervalo de elementos de array que contiene el número de elementos especificado en count y termina en startIndex, si se encuentra; en caso contrario, el límite inferior de la matriz menos 1.The index of the last occurrence of value within the range of elements in array that contains the number of elements specified in count and ends at startIndex, if found; 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

En el ejemplo de código siguiente se muestra cómo determinar el índice de la última aparición de un elemento especificado en una matriz.The following code example shows how to determine the index of the last occurrence of a specified element in an array. Tenga en cuenta que el LastIndexOf método es una búsqueda hacia atrás; por lo tanto, count debe ser menor o igual a (startIndex menos el límite inferior de la matriz, más 1).Note that the LastIndexOf method is a backward search; therefore, count must be less than or equal to (startIndex minus the lower bound of the array plus 1).

using namespace System;
void PrintIndexAndValues( Array^ myArray );

void main()
{
   // Creates and initializes a new Array instance with three elements of the same value.
   Array^ myArray = Array::CreateInstance( String::typeid, 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 instance contains the following values:" );
   PrintIndexAndValues( myArray );

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

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

   // Searches for the last occurrence of the duplicated value in a section of the Array.  
   // Note that the start index is greater than the end index because the search is done backward.
   myIndex = Array::LastIndexOf( myArray, myString, 10, 6 );
   Console::WriteLine(  "The last occurrence of \"{0}\" between index 5 and index 10 is at index {1}.", myString, myIndex );
}

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 instance 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 last occurrence of "the" is at index 10.
 The last occurrence of "the" between the start and index 8 is at index 6.
 The last occurrence of "the" between index 5 and index 10 is at index 10.
 */
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 last occurrence of the duplicated value.
      String myString = "the";
      int myIndex = Array.LastIndexOf( myArray, myString );
      Console.WriteLine( "The last occurrence of \"{0}\" is at index {1}.", myString, myIndex );

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

      // Searches for the last occurrence of the duplicated value in a section of the Array.
      // Note that the start index is greater than the end index because the search is done backward.
      myIndex = Array.LastIndexOf( myArray, myString, 10, 6 );
      Console.WriteLine( "The last occurrence of \"{0}\" between index 5 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 last occurrence of "the" is at index 10.
The last occurrence of "the" between the start and index 8 is at index 6.
The last occurrence of "the" between index 5 and index 10 is at index 10.
*/
Imports System
Imports Microsoft.VisualBasic

Public Class SamplesArray    
    
    Public Shared Sub Main()
        
        ' Creates and initializes a new Array with three elements of
        ' the same value.
        Dim myArray As Array = Array.CreateInstance(GetType(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 last occurrence of the duplicated value.
        Dim myString As String = "the"
        Dim myIndex As Integer = Array.LastIndexOf(myArray, myString)
        Console.WriteLine("The last occurrence of ""{0}"" is at index {1}.", _
           myString, myIndex)
        
        ' Searches for the last occurrence of the duplicated value in the first
        ' section of the Array.
        myIndex = Array.LastIndexOf(myArray, myString, 8)
        Console.WriteLine("The last occurrence of ""{0}"" between the start " _
           + "and index 8 is at index {1}.", myString, myIndex)
        
        ' Searches for the last occurrence of the duplicated value in a section
        ' of the Array.  Note that the start index is greater than the end
        ' index because the search is done backward.
        myIndex = Array.LastIndexOf(myArray, myString, 10, 6)
        Console.WriteLine("The last occurrence of ""{0}"" between index 5 " _
           + "and index 10 is at index {1}.", myString, myIndex)
    End Sub
    
    
    Public Shared Sub PrintIndexAndValues(myArray As Array)
        Dim i As Integer
        For i = myArray.GetLowerBound(0) To myArray.GetUpperBound(0)
            Console.WriteLine(ControlChars.Tab + "[{0}]:" + ControlChars.Tab _
               + "{1}", i, myArray.GetValue(i))
        Next i
    End Sub
End Class

' 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 last occurrence of "the" is at index 10.
' The last occurrence of "the" between the start and index 8 is at index 6.
' The last occurrence of "the" between index 5 and index 10 is at index 10. 

Comentarios

Unidimensional Array es la búsqueda hacia atrás, empezando en startIndex hasta startIndex menos count más 1, si count es mayor que 0.The one-dimensional Array is searched backward starting at startIndex and ending at startIndex minus count plus 1, if count is greater than 0.

Los elementos se comparan con el valor especificado mediante el Object.Equals método.The elements are compared to the specified value using the Object.Equals method. Si el tipo de elemento es un tipo no intrínseco (definido por el usuario), elEquals se utiliza la implementación de ese tipo.If the element type is a nonintrinsic (user-defined) type, theEquals implementation of that type is used.

Como la mayoría de las matrices tienen un límite inferior de cero, este método normalmente devuelve-1 cuando value no se encuentra.Since most arrays will have a lower bound of zero, this method would generally return -1 when value is not found. En el extraño caso de que el límite inferior de la matriz es igual a Int32.MinValue y value no se encuentra, este método devuelve Int32.MaxValue, que es System.Int32.MinValue - 1.In the rare case that the lower bound of the array is equal to Int32.MinValue and value is not found, this method returns Int32.MaxValue, which is System.Int32.MinValue - 1.

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

En la versión 2.0 de .NET Framework, este método utiliza la Equals y CompareTo métodos de la Array para determinar si el Object especificado por el value parámetro existe.In the .NET Framework version 2.0, this method uses the Equals and CompareTo methods of the Array to determine whether the Object specified by the value parameter exists. En las versiones anteriores de .NET Framework, esta determinación se realiza mediante el uso de la Equals y CompareTo métodos de la value Object propio.In the earlier versions of the .NET Framework, this determination was made by using the Equals and CompareTo methods of the valueObject itself.

Consulte también:

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

Busca el objeto especificado y devuelve el índice de la última aparición de toda la Array.Searches for the specified object and returns the index of the last occurrence within the entire Array.

public:
generic <typename T>
 static int LastIndexOf(cli::array <T> ^ array, T value);
public static int LastIndexOf<T> (T[] array, T value);
static member LastIndexOf : 'T[] * 'T -> int
Public Shared Function LastIndexOf(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[]

Array unidimensional de base cero en la que se realizará la búsqueda.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 última aparición de value en toda la array, si se encuentra; en caso contrario, -1.The zero-based index of the last occurrence of value within the entire array, if found; otherwise, -1.

Excepciones

Ejemplos

El ejemplo de código siguiente muestra tres sobrecargas genéricas de los LastIndexOf método.The following code example demonstrates all three generic overloads of the LastIndexOf 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 LastIndexOf<T>(T[], T) sobrecarga del método busca en toda la matriz desde el final y encuentra la segunda aparición de la cadena.The LastIndexOf<T>(T[], T) method overload searches the entire array from the end, and finds the second occurrence of the string. El LastIndexOf<T>(T[], T, Int32) sobrecarga del método se utiliza para buscar el principio con versiones anteriores de matriz en la posición de índice 3 y continuando hasta el principio de la matriz y busca la primera aparición de la cadena.The LastIndexOf<T>(T[], T, Int32) method overload is used to search the array backward beginning with index location 3 and continuing to the beginning of the array, and finds the first occurrence of the string. Por último, el LastIndexOf<T>(T[], T, Int32, Int32) sobrecarga del método se utiliza para buscar un intervalo de cuatro entradas, comenzando en la posición de índice 4 y avanzando hacia atrás (es decir, busca los elementos en ubicaciones 1, 2, 3 y 4); esta búsqueda devuelve -1 porque no hay ninguna instancia de la búsqueda cadena en ese intervalo.Finally, the LastIndexOf<T>(T[], T, Int32, Int32) method overload is used to search a range of four entries, beginning at index location 4 and extending backward (that is, it searches the items at locations 4, 3, 2, and 1); this search 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.LastIndexOf(dinosaurs, \"Tyrannosaurus\"): {0}", 
        Array::LastIndexOf(dinosaurs, "Tyrannosaurus"));

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

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

/* This code example produces the following output:

Tyrannosaurus
Amargasaurus
Mamenchisaurus
Brachiosaurus
Deinonychus
Tyrannosaurus
Compsognathus

Array.LastIndexOf(dinosaurs, "Tyrannosaurus"): 5

Array.LastIndexOf(dinosaurs, "Tyrannosaurus", 3): 0

Array.LastIndexOf(dinosaurs, "Tyrannosaurus", 4, 4): -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.LastIndexOf(dinosaurs, \"Tyrannosaurus\"): {0}", 
            Array.LastIndexOf(dinosaurs, "Tyrannosaurus"));

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

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

/* This code example produces the following output:

Tyrannosaurus
Amargasaurus
Mamenchisaurus
Brachiosaurus
Deinonychus
Tyrannosaurus
Compsognathus

Array.LastIndexOf(dinosaurs, "Tyrannosaurus"): 5

Array.LastIndexOf(dinosaurs, "Tyrannosaurus", 3): 0

Array.LastIndexOf(dinosaurs, "Tyrannosaurus", 4, 4): -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.LastIndexOf(dinosaurs, ""Tyrannosaurus""): {0}", _
            Array.LastIndexOf(dinosaurs, "Tyrannosaurus"))

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

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

    End Sub
End Class

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

Comentarios

El Array se realiza hacia atrás a partir del último elemento y terminando en el primer elemento.The Array is searched backward starting at the last element and ending at the first element.

Los elementos se comparan con el valor especificado mediante el Object.Equals método.The elements are compared to the specified value using the Object.Equals method. Si el tipo de elemento es un tipo no intrínseco (definido por el usuario), el Equals se utiliza la implementación de ese tipo.If the element type is a nonintrinsic (user-defined) type, the Equals implementation of that type is used.

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:

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

Busca el objeto especificado y devuelve el índice de la última aparición en el intervalo de elementos de la Array que se extiende desde el primer elemento hasta el índice especificado.Searches for the specified object and returns the index of the last occurrence within the range of elements in the Array that extends from the first element to the specified index.

public:
generic <typename T>
 static int LastIndexOf(cli::array <T> ^ array, T value, int startIndex);
public static int LastIndexOf<T> (T[] array, T value, int startIndex);
static member LastIndexOf : 'T[] * 'T * int -> int
Public Shared Function LastIndexOf(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[]

Array unidimensional de base cero en la que se realizará la búsqueda.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 hacia atrás.The zero-based starting index of the backward search.

Devoluciones

Índice de base cero de la última aparición de value dentro del intervalo de elementos de array que abarca desde el primer elemento hasta startIndex, si se encuentra; de lo contrario, -1.The zero-based index of the last occurrence of value within the range of elements in array that extends from the first element to startIndex, 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 de código siguiente muestra tres sobrecargas genéricas de los LastIndexOf método.The following code example demonstrates all three generic overloads of the LastIndexOf 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 LastIndexOf<T>(T[], T) sobrecarga del método busca en toda la matriz desde el final y encuentra la segunda aparición de la cadena.The LastIndexOf<T>(T[], T) method overload searches the entire array from the end, and finds the second occurrence of the string. El LastIndexOf<T>(T[], T, Int32) sobrecarga del método se utiliza para buscar el principio con versiones anteriores de matriz en la posición de índice 3 y continuando hasta el principio de la matriz y busca la primera aparición de la cadena.The LastIndexOf<T>(T[], T, Int32) method overload is used to search the array backward beginning with index location 3 and continuing to the beginning of the array, and finds the first occurrence of the string. Por último, el LastIndexOf<T>(T[], T, Int32, Int32) sobrecarga del método se utiliza para buscar un intervalo de cuatro entradas, comenzando en la posición de índice 4 y avanzando hacia atrás (es decir, busca los elementos en ubicaciones 1, 2, 3 y 4); esta búsqueda devuelve -1 porque no hay ninguna instancia de la búsqueda cadena en ese intervalo.Finally, the LastIndexOf<T>(T[], T, Int32, Int32) method overload is used to search a range of four entries, beginning at index location 4 and extending backward (that is, it searches the items at locations 4, 3, 2, and 1); this search 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.LastIndexOf(dinosaurs, \"Tyrannosaurus\"): {0}", 
        Array::LastIndexOf(dinosaurs, "Tyrannosaurus"));

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

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

/* This code example produces the following output:

Tyrannosaurus
Amargasaurus
Mamenchisaurus
Brachiosaurus
Deinonychus
Tyrannosaurus
Compsognathus

Array.LastIndexOf(dinosaurs, "Tyrannosaurus"): 5

Array.LastIndexOf(dinosaurs, "Tyrannosaurus", 3): 0

Array.LastIndexOf(dinosaurs, "Tyrannosaurus", 4, 4): -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.LastIndexOf(dinosaurs, \"Tyrannosaurus\"): {0}", 
            Array.LastIndexOf(dinosaurs, "Tyrannosaurus"));

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

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

/* This code example produces the following output:

Tyrannosaurus
Amargasaurus
Mamenchisaurus
Brachiosaurus
Deinonychus
Tyrannosaurus
Compsognathus

Array.LastIndexOf(dinosaurs, "Tyrannosaurus"): 5

Array.LastIndexOf(dinosaurs, "Tyrannosaurus", 3): 0

Array.LastIndexOf(dinosaurs, "Tyrannosaurus", 4, 4): -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.LastIndexOf(dinosaurs, ""Tyrannosaurus""): {0}", _
            Array.LastIndexOf(dinosaurs, "Tyrannosaurus"))

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

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

    End Sub
End Class

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

Comentarios

El Array es la búsqueda hacia atrás, empezando en startIndex y terminando en el primer elemento.The Array is searched backward starting at startIndex and ending at the first element.

Los elementos se comparan con el valor especificado mediante el Object.Equals método.The elements are compared to the specified value using the Object.Equals method. Si el tipo de elemento es un tipo no intrínseco (definido por el usuario), el Equals se utiliza la implementación de ese tipo.If the element type is a nonintrinsic (user-defined) type, the Equals implementation of that type is used.

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

Consulte también:

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

Busca el objeto especificado y devuelve el índice de la última aparición en el intervalo de elementos de la Array que contiene el número de elementos especificado y termina en el índice especificado.Searches for the specified object and returns the index of the last occurrence within the range of elements in the Array that contains the specified number of elements and ends at the specified index.

public:
generic <typename T>
 static int LastIndexOf(cli::array <T> ^ array, T value, int startIndex, int count);
public static int LastIndexOf<T> (T[] array, T value, int startIndex, int count);
static member LastIndexOf : 'T[] * 'T * int * int -> int
Public Shared Function LastIndexOf(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[]

Array unidimensional de base cero en la que se realizará la búsqueda.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 hacia atrás.The zero-based starting index of the backward search.

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 última aparición de value dentro del intervalo de elementos de array que contiene el número de elementos especificado en count y termina en startIndex, si se encuentra; de lo contrario, -1.The zero-based index of the last occurrence of value within the range of elements in array that contains the number of elements specified in count and ends at startIndex, 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 de código siguiente muestra tres sobrecargas genéricas de los LastIndexOf método.The following code example demonstrates all three generic overloads of the LastIndexOf 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 LastIndexOf<T>(T[], T) sobrecarga del método busca en toda la matriz desde el final y encuentra la segunda aparición de la cadena.The LastIndexOf<T>(T[], T) method overload searches the entire array from the end, and finds the second occurrence of the string. El LastIndexOf<T>(T[], T, Int32) sobrecarga del método se utiliza para buscar el principio con versiones anteriores de matriz en la posición de índice 3 y continuando hasta el principio de la matriz y busca la primera aparición de la cadena.The LastIndexOf<T>(T[], T, Int32) method overload is used to search the array backward beginning with index location 3 and continuing to the beginning of the array, and finds the first occurrence of the string. Por último, el LastIndexOf<T>(T[], T, Int32, Int32) sobrecarga del método se utiliza para buscar un intervalo de cuatro entradas, comenzando en la posición de índice 4 y avanzando hacia atrás (es decir, busca los elementos en ubicaciones 1, 2, 3 y 4); esta búsqueda devuelve -1 porque no hay ninguna instancia de la búsqueda cadena en ese intervalo.Finally, the LastIndexOf<T>(T[], T, Int32, Int32) method overload is used to search a range of four entries, beginning at index location 4 and extending backward (that is, it searches the items at locations 4, 3, 2, and 1); this search 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.LastIndexOf(dinosaurs, \"Tyrannosaurus\"): {0}", 
        Array::LastIndexOf(dinosaurs, "Tyrannosaurus"));

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

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

/* This code example produces the following output:

Tyrannosaurus
Amargasaurus
Mamenchisaurus
Brachiosaurus
Deinonychus
Tyrannosaurus
Compsognathus

Array.LastIndexOf(dinosaurs, "Tyrannosaurus"): 5

Array.LastIndexOf(dinosaurs, "Tyrannosaurus", 3): 0

Array.LastIndexOf(dinosaurs, "Tyrannosaurus", 4, 4): -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.LastIndexOf(dinosaurs, \"Tyrannosaurus\"): {0}", 
            Array.LastIndexOf(dinosaurs, "Tyrannosaurus"));

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

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

/* This code example produces the following output:

Tyrannosaurus
Amargasaurus
Mamenchisaurus
Brachiosaurus
Deinonychus
Tyrannosaurus
Compsognathus

Array.LastIndexOf(dinosaurs, "Tyrannosaurus"): 5

Array.LastIndexOf(dinosaurs, "Tyrannosaurus", 3): 0

Array.LastIndexOf(dinosaurs, "Tyrannosaurus", 4, 4): -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.LastIndexOf(dinosaurs, ""Tyrannosaurus""): {0}", _
            Array.LastIndexOf(dinosaurs, "Tyrannosaurus"))

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

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

    End Sub
End Class

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

Comentarios

El Array es la búsqueda hacia atrás, empezando en startIndex hasta startIndex menos count más 1, si count es mayor que 0.The Array is searched backward starting at startIndex and ending at startIndex minus count plus 1, if count is greater than 0.

Los elementos se comparan con el valor especificado mediante el Object.Equals método.The elements are compared to the specified value using the Object.Equals method. Si el tipo de elemento es un tipo no intrínseco (definido por el usuario), el Equals se utiliza la implementación de ese tipo.If the element type is a nonintrinsic (user-defined) type, the Equals implementation of that type is used.

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:

Se aplica a