Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting indexes of all matching items [duplicate]

Tags:

c#

linq

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);
like image 486
RoadieRich Avatar asked Apr 09 '13 15:04

RoadieRich


1 Answers

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++;
    }
}
like image 97
MarcinJuraszek Avatar answered Oct 03 '22 14:10

MarcinJuraszek