Possible Duplicate:
Why is there not a ForEach extension method on the IEnumerable interface?
First, let me specify I am refering to the List<T> method and not the C# keyword. What would be Microsoft’s reasoning for having the Foreach method on the List<T> collection but no other collection/enumerable type, specifically IEnumerable<T>?
I just discovered this method the other day, and found it to be very nice syntax for replacing traditional foreach loops that only perform one or 2 lines of methods on each object.
It seems like it would be fairly trivial to create an extension method that ,performs this same function. I guess I’m looking at why MS made this decision and based on that if I should just make an extension method.
Eric Lippert has responded to this question numerous times, including on his blog.
His response has been that
ForEach()is something you use explicitly for its side effects – whereas LINQ is largely intended to be a side-effect free API to define projections and manipulations on sequences.Outside of uses like parallel loops, the functional
ForEachsyntax doesn’t add much in the way of expressive power, and it is slightly less efficient than a regularforeachloop due to the delegate invocations.If you really, really want a
ForEachforIEnumerable<T>, it’s not hard to write one: