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
foreachstatement in C# language itself.As Jon hints (and Eric explicitly states), LINQ designers wanted to keep methods side-effect-free, whereas
ForEachwould break this contract.There actually is a
ForEachmethod that does applies given predicate inList<T>andArrayclasses 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'
foreachis 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 returnsTandAction<T>denotes avoidmethod that acceptsT.