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);
RoadieRich
  • 6,330
  • 3
  • 35
  • 52

1 Answers1

10

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++;
    }
}
MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263