How to get the index of an element in C# LINQ
By FoxLearn 1/22/2025 8:44:16 AM 278
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, linq get index of item in list c#
// linq index c# indexof 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
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, linq index c# indexof
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.
Categories
Popular Posts
AdminKit Bootstrap 5 HTML5 UI Kits Template
11/17/2024
Spica Admin Dashboard Template
11/18/2024