How to get index of element in array C# LINQ
By FoxLearn 12/12/2024 1:09:05 AM 169
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, Find the index of an item in an array using LINQ
int[] numbers = { 10, 20, 30, 40, 50 }; int elementToFind = 40; // linq select index of item in array 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 create an anonymous object containing both the value and its index using Select
. Then, we will use Where
to filter the collection and find the object that matches the desired value. The Select
method will extract the index of the matched object. Finally, we use FirstOrDefault
to get the first index found.
- How to get the index of an element in C# LINQ
- Using LINQ's Distinct() on a Specific Property
- Difference Between Select and SelectMany in LINQ
- Group by in LINQ
- How to group by multiple columns using LINQ
- Using LINQ to remove elements from a List<T>
- Using LINQ to Query DataTables
- IEnumerable<T> vs IQueryable<T>
Categories
Popular Posts
Modular Admin Template
11/14/2024
Star Admin Dashboard Template
11/17/2024
Gentella Admin Template
11/14/2024
Material Lite Admin Template
11/14/2024
Admin Tailwind CSS Admin Dashboard Template
11/18/2024