How to get index of element in array C# LINQ

By FoxLearn 10/25/2024 9:22:00 AM   80
To get the index of an element in an array using LINQ in C#, you can use the Select method along with Where to find the index.

For example:

int[] numbers = { 10, 20, 30, 40, 50 };
int elementToFind = 40;

int index = numbers.Select((value, idx) => new { value, idx })
               .Where(x => x.value == elementToFind)
               .Select(x => x.idx)
               .FirstOrDefault();

Console.WriteLine(index);//Output 3

First, We will creates an anonymous object with both the value and its index by using select, then use where to filter the collection to find the object that matches the desired value. The select will extract the index of the matched object.

Next, Using FirstOrDefault to get the first index found.