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



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
Updated on: 2020-06-22T13:59:37+05:30

403 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements