Inspired by another question asking about the missing Zip
function:
Why is there no ForEach
extension method in the Enumerable
class? Or anywhere? The only class that gets a ForEach
method is List<>
. Is there a reason why it's missing (performance)?
I've always wondered that myself, that is why that I always carry this with me:
Nice little extension method.
Partially it's because the language designers disagree with it from a philosophical perspective.
https://blogs.msdn.microsoft.com/ericlippert/2009/05/18/foreach-vs-foreach/
I would like to expand on Aku's answer.
If you want to call a method for the sole purpose of it's side-effect without iterating the whole enumerable first you can use this:
Note that the MoreLINQ NuGet provides the
ForEach
extension method you're looking for (as well as aPipe
method which executes the delegate and yields its result). See:The discussion here gives the answer:
Basically the decision was made to keep the extension methods functionally "pure". A ForEach would encourage side-effects when using the Enumerable extension methods, which was not the intent.
One workaround is to write
.ToList().ForEach(x => ...)
.pros
Easy to understand - reader only needs to know what ships with C#, not any additional extension methods.
Syntactic noise is very mild (only adds a little extranious code).
Doesn't usually cost extra memory, since a native
.ForEach()
would have to realize the whole collection, anyway.cons
Order of operations isn't ideal. I'd rather realize one element, then act on it, then repeat. This code realizes all elements first, then acts on them each in sequence.
If realizing the list throws an exception, you never get to act on a single element.
If the enumeration is infinite (like the natural numbers), you're out of luck.