Select the index of a specific object via LINQ

This will search for the index of an object in a collection depending on a specific criteria.
When the object is not found in the collection, it will return an index with value -1.


string searchValue = "d";
List<string> items = new List<string>() { "a", "b", "c", "d", "e" };

int foundIndex = items.Select((x, i) => new { x, i })
.Where(x => x.x == searchValue)
.Select(x => x.i)
.DefaultIfEmpty(-1)
.First();

// specific code for LINQPad
foundIndex.Dump();

The result will be 3, because “d” has index 3 in the collection.

Advertisements