Searches for the specified object and returns the index of the last occurrence within the entire one-dimensional Array.
- array
- The one-dimensional Array to search.
- value
- The object to locate in array.
The index of the last occurrence of value within the entire array, if found; otherwise, the lower bound of the array minus 1.
Type Reason ArgumentNullException array is null . RankException array has more than one dimension.
The one-dimensional Array is searched backward starting at the last element and ending at the first element.
The elements are compared to the specified value using the object.Equals(object) method. If the element type is a nonintrinsic (user-defined) type, the Equals implementation of that type is used.
Since most arrays will have a lower bound of zero, this method would generally return –1 when value is not found. In the rare case that the lower bound of the array is equal to int.MinValue and value is not found, this method returns int.MaxValue, which is System.Int32.MinValue - 1.
This method is an O(n) operation, where n is the Array.Length of array.
In the .NET Framework version 2.0, this method uses the object.Equals(object) and IComparable.CompareTo(object) methods of the Array to determine whether the object specified by the value parameter exists. In the earlier versions of the .NET Framework, this determination was made by using the object.Equals(object) and IComparable.CompareTo(object) methods of the value object itself.
IComparable.CompareTo(object) methods of the item parameter on the objects in the collection.
The following example demonstrates the Array.LastIndexOf(Array, object) method.
C# Example
using System; public class ArrayLastIndexOfExample { public static void Main() { int[] intAry = { 0, 1, 2, 0, 1 }; Console.Write( "The values of the array are: "); foreach( int i in intAry ) Console.Write( "{0,5}", i ); Console.WriteLine(); int j = Array.LastIndexOf( intAry, 1 ); Console.WriteLine( "The last occurrence of 1 is at index {0}", j ); } }
The output is
The values of the array are: 0 1 2 0 1