C# program to find the last matching element in an array

CsharpProgrammingServer Side Programming

To find the last matching element, use the Array.LastIndexOf method. Returns -1 if the element isn’t present in the integer array.

The following is the array −

int[] val = { 97, 45, 76, 21, 89, 45 };

Now, let’s say you need to search the last Index of element 45. For that, use Array.LastIndexOf() method −

int res = Array.LastIndexOf(val, 45);

The following is an example −

Example

 Live Demo

using System;
using System.Text;
public class Demo {
   public static void Main() {
      int[] val = { 97, 45, 76, 21, 89, 45 };
      // last Index of element 45
      int res = Array.LastIndexOf(val, 45);
      // Display the index
      Console.WriteLine("Index of element 45 is = "+res);
   }
}

Output

Index of element 45 is = 5
raja
Published on 04-Sep-2018 15:51:41
Advertisements