How to get the index of an element in C# LINQ

By FoxLearn 12/12/2024 1:08:59 AM   213
In C#, you can use LINQ to find the index of an element in a list by utilizing the Select method.

You can use Select to pair each element with its index and then filter for the desired element.

For example:

List<int> numbers = new List<int> { 10, 20, 30, 40, 50 };
int target = 30;
int index = numbers
    .Select((value, idx) => new { value, idx })
    .FirstOrDefault(x => x.value == target)?.idx ?? -1;
Console.WriteLine(index); // Output: 2

Use Select combined with FirstOrDefault.

To find the index of an element in a list using LINQ, you can leverage the Enumerable.Any(predicate) method alongside a closure technique. Although Any() returns a boolean indicating whether the element exists, you can use an external counter variable within the predicate to track the index.

For example:

List<int> numbers = new List<int> { 10, 20, 30, 40, 50 };
int target = 30;
int index = -1; // Initialize index variable
int result = numbers.Any(p => { ++index; return p == target; }) ? index : -1;
Console.WriteLine(result);

This method allows you to find an element’s index by using a counter in the Any() predicate, enabling the iteration through the list while capturing the index of the found element.