C# Tips

C# Tip Article

Finding element index of a list using LINQ

One interesting way of finding an element index of a list using LINQ.

Enumerable.Any(predicate) method iterates all elements of a collection until it finds the matching element. But Enumerable.Any() method itself returns boolean value, indicating Found or NotFound.

In order to get element index, closure technique can be used. That is, an external counter variable is injected to predicate of Any() method. Here is an example.

var list = new List() { "a", "b", "c", "d", "e" };

int i = -1;
int result = list.Any(p => { ++i; return p == "c"; }) ? i : -1;


This example finds c from a list a~e. Every time Any() iterates each element of the list, variable i increments.

Since the list has c, the iteration stops at the 3rd step. So variable i becomes 2, which is what is expected as an element index.