First select each item with its index, then filter the items, and finally extract the original index:
var result = orderedList
.Select((x, i) => new { Item = x, Index = i })
.Where(itemWithIndex => itemWithIndex.Item.StartsWith("g"))
.FirstOrDefault();
int index= -1;
if (result != null)
index = result.Index;
Test bed:
class Program
{
static void Main(string[] args)
{
var orderedList = new List<string>
{
"foo", "bar", "baz", "qux", "quux",
"corge", "grault", "garply", "waldo",
"fred", "plugh", "xyzzy", "thud"
}.OrderBy(x => x);
// bar, baz, corge, foo, fred, garply, grault,
// plugh, quux, qux, thud, waldo, xyzzy
// Find the index of the first element beginning with g .
var result = orderedList
.Select((x, i) => new { Item = x, Index = i })
.Where(itemWithIndex => itemWithIndex.Item.StartsWith("g"))
.FirstOrDefault();
int index= -1;
if (result != null)
index = result.Index;
Console.WriteLine("Index: " + index);
}
}
Output:
Index: 5