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);
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++;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With