6

I want to get the index of all items in an enumerable that match a given condition. Is there a cleaner way than this?

var indexes = list.Select((item, index) => new { Item = item, Index = index }).Where(o => Condition(o.Item)).Select(o => o.Index);
2

1 Answer 1

11

Using standard LINQ to Object methods - no, there's not. You only can improve readability by splitting your query into couple lines:

var indexes = list.Select((item, index) => new { Item = item, Index = index })
                  .Where(o => Condition(o.Item))
                  .Select(o => o.Index);

However, you can write an Extension Method for that:

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++;
    }
}
1
  • Seeing as I've already got a rather extensive library of extensions, I like this solution.
    – RoadieRich
    Apr 9, 2013 at 15:13

Not the answer you're looking for? Browse other questions tagged or ask your own question.