Are there std::for_each algoritm analog in C# (Linq to Objects), to be able to pass Func<>
into it? Like
sequence.Each(p => p.Some());
instead of
foreach(var elem in sequence)
{
elem.Some();
}
Are there std::for_each algoritm analog in C# (Linq to Objects), to be able to pass Func<>
into it? Like
sequence.Each(p => p.Some());
instead of
foreach(var elem in sequence)
{
elem.Some();
}
There is a
foreach
statement in C# language itself.As Jon hints (and Eric explicitly states), LINQ designers wanted to keep methods side-effect-free, whereas
ForEach
would break this contract.There actually is a
ForEach
method that does applies given predicate inList<T>
andArray
classes but it was introduced in .NET Framework 2.0 and LINQ only came with 3.5. They are not related.After all, you can always come up with your own extension method:
I agree this is useful in case you already have a single parameter method and you want to run it for each element.
However in other cases I believe good ol'
foreach
is much cleaner and concise.By the way, a single-paramether void method is not a
Func<T>
but anAction<T>
.Func<T>
denotes a function that returnsT
andAction<T>
denotes avoid
method that acceptsT
.