Getting a collection of index values using a LINQ query

Guy picture Guy · Oct 26, 2008 · Viewed 10.5k times · Source

Is there a better way to do this?

string[] s = {"zero", "one", "two", "three", "four", "five"};

var x = 
s
.Select((a,i) => new {Value = a, Index = i})
.Where(b => b.Value.StartsWith("t"))
.Select(c => c.Index);

i.e. I'm looking for a more efficient or more elegant way to get the positions of the items matching the criteria.

Answer

Jon Skeet picture Jon Skeet · Oct 26, 2008

You could easily add your own extension method:

public static IEnumerable<int> IndexesWhere<T>(this IEnumerable<T> source, Func<T, bool> predicate)
{
    int index=0;
    foreach (T element in source)
    {
        if (predicate(element))
        {
            yield return index;
        }
        index++;
    }
}

Then use it with:

string[] s = {"zero", "one", "two", "three", "four", "five"};
var x = s.IndexesWhere(t => t.StartsWith("t"));