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)?
Is it me or is the List<T>.Foreach pretty much been made obsolete by Linq. Originally there was
where Y simply had to be IEnumerable (Pre 2.0), and implement a GetEnumerator(). If you look at the MSIL generated you can see that it is exactly the same as
(See http://alski.net/post/0a-for-foreach-forFirst-forLast0a-0a-.aspx for the MSIL)
Then in DotNet2.0 Generics came along and the List. Foreach has always felt to me to be an implementation of the Vistor pattern, (see Design Patterns by Gamma, Helm, Johnson, Vlissides).
Now of course in 3.5 we can instead use a Lambda to the same effect, for an example try http://dotnet-developments.blogs.techtarget.com/2008/09/02/iterators-lambda-and-linq-oh-my/
@Coincoin
The real power of the foreach extension method involves reusability of the
Action<>
without adding unnecessary methods to your code. Say that you have 10 lists and you want to perform the same logic on them, and a corresponding function doesn't fit into your class and is not reused. Instead of having ten for loops, or a generic function that is obviously a helper that doesn't belong, you can keep all of your logic in one place (theAction<>
. So, dozens of lines get replaced withetc...
The logic is in one place and you haven't polluted your class.
No one has yet pointed out that ForEach<T> results in compile time type checking where the foreach keyword is runtime checked.
Having done some refactoring where both methods were used in the code, I favor .ForEach, as I had to hunt down test failures / runtime failures to find the foreach problems.
ForEach method was added before LINQ. If you add ForEach extension, it will never be called for List instances because of extension methods constraints. I think the reason it was not added is to not interference with existing one.
However, if you really miss this little nice function, you can roll out your own version
In 3.5, all the extension methods added to IEnumerable are there for LINQ support (notice that they are defined in the System.Linq.Enumerable class). In this post, I explain why foreach doesn't belong in LINQ: Existing LINQ extension method similar to Parallel.For?
While I agree that it's better to use the built-in
Exampleforeach
construct in most cases, I find the use of this variation on the ForEach<> extension to be a little nicer than having to manage the index in a regularforeach
myself:Would give you: