get the index of an ienumerable element in csharp

You can use the Select() extension method to project each element into a tuple with its index, then use the FirstOrDefault() extension method to find the first element in the sequence that matches a specific condition (in this case, the element itself), and finally return the index of that element.

main.cs
var enumerable = new[] { "foo", "bar", "baz" };
var element = "bar";

var index = enumerable
    .Select((e, i) => new { Element = e, Index = i })
    .FirstOrDefault(x => x.Element == element)?
    .Index;

if (index.HasValue)
{
    Console.WriteLine($"The index of '{element}' is {index}");
}
else
{
    Console.WriteLine($"The element '{element}' was not found in the enumerable");
}
387 chars
17 lines

Output:

main.cs
The index of 'bar' is 1
24 chars
2 lines

gistlibby LogSnag