I've got a List<>
in C# and I want to check that all elements of the list meet some condition. This condition depends on the element in the list, as well as that elements index in the list.
It doesn't look like .All(..)
has an overload that gives the index? I want to do something like:
bool result = list.All((element, index) => {
// for example:
return element != null && index % 2 == 0;
// (my actual condition is more complicated, but that's not the point of the question)
});
But that doesn't work, because there's no version of .All(...)
that provides the index. I've also come up with:
bool result = list.Select((element, index) => {
// for example:
return element != null && index % 2 == 0;
}).All(identity => identity);
Which works but .All(identity => identity)
makes me die a little inside.
Is there a more idiomatic way to do this?
In .NET 9 you will have Enumerable.Index()
, which will allow you to write this:
bool result = strings.Index().All(element =>
element.Item != null
&& element.Index % 2 == 0);
If you don't want to wait two weeks for .NET 9 (or don't intend to use it) you can write your own version of .Index()
for now:
static class MyEnumerableExt
{
public static IEnumerable<(int Index, T Item)> Index<T>(this IEnumerable<T> source)
{
return source.Select((item, index) => (index, item));
}
}