public static class LoopExtensions
{
public static void ForEach<T>(this IEnumerable<T> values, Action<T> action)
{
foreach (var v in values)
action(v);
}
}
Fork
5 Feedback
Fredrik, I believe that this method goes against the spirit of LINQ. - @luisabreu Sunday 11, 2010 3:35 PM
Basically, this is just another version of the Update extension method that has been around since 2007. - JonnyBee Tuesday 13, 2010 9:36 AMYou must log in before you can give any feedback
0
Why do you think it's against the spirit of LINQ? It's just an extension method.. ;)
0
I too like this extension method, but there is a good reason for it not being implemented by default - basically, a LINQ call is supposed to be "functional" in nature without side-effects. The ForEach extension however is pretty much all about the side-effects.
This blog post discusses why in more detail.
But in any case, the extension method is quite useful!
0
The blog post tries to make the extension method harder to read than it is:
Enumerable.ForEach((Foo foo) => { stuff ;});
It would rather be:
Enumerable.ForEach(foo => stuff);
I'm also having a hard time seeing why every single extension method on an IEnumerable must conform to functional style..
Should IEnumerable be protected by specific extension guidelines that other types don't have to conform to?
0
0
Eric's post explains why MS didn't add the Foreach extension method. Btw, why not:
foreach( var x in collection) { Stuff; }
Isn't this also one line, right? and look: no method invocation. that means it could be faster than the extension method approach...
I guess we should also be careful so that we don't become "extension method alcoholics"...
0
This is what I would like to have:
ForEach.Collection.Do(Stuff);
I have done it with DynamicObject but the code was ugly.
0
There has been an List.ForEach since .NET 2.0. But I to don't feel that this is the right place for an extension methods. I think I just like the functional immutability of the other IEnumerable extensions and also, people are used to the standard foreach(var in xxx) syntax. This, I think, only confuses.
0
This actually dates back to 2008...
At least now is a good time to join the The “Anti-For” Campaign :-D
1
You must log in before you can post a comment


939
0

Mark '.net' tag as 'like'
Mark '.net' tag as 'ignore'