Array.LastIndexOf(T[], T) Method in C#


The Array.LastIndexOf() method in C# is used to search for the specified object and returns the index of the last occurrence within the entire Array.

Syntax

Following is the syntax −

public static int LastIndexOf<T> (T[] array, T val);

Above, the parameter arr is the one-dimensional, zero-based Array to search, whereas Val is the object to locate in an array.

Example

Let us now see an example to implement the Array.LastIndexOf() method −

using System;
public class Demo{
   public static void Main(){
      Console.WriteLine("Array elements...");
      string[] arr = { "car", "bike", "truck", "bus"};
      for (int i = 0; i < arr.Length; i++){
         Console.Write("{0} ", arr[i]);
      }
      Console.WriteLine();
      int lastIndex = Array.LastIndexOf(arr, "bus");
      Console.WriteLine("Last Ocurrence of element bus is at index = "+lastIndex);
   }
}

Output

This will produce the following output −

Array elements...
car bike truck bus
Last Ocurrence of element bus is at index = 3
raja
Published on 07-Nov-2019 06:12:00
Advertisements