IEnumerable<T> and ForEach()
Why is there no ForEach() extension method defined for IEnumerable<T> in System.Linq.Enumerable for .NET 3.5? There is a ForEach() on Array and List<T>, but not for IEnumerable<T> which would seem a fairly natural place for it.
public static class Extensions {
public static void ForEach<T>(this IEnumerable<T> source, Action<T> action) {
foreach (var item in source) {
action(item);
}
}
}
For some reason, when I'm in LINQy mode, my natural reaction is to try ForEach() over foreach, and I'm always a bit surprised when it doesn't work for IEnumerable<T>:
//Lambda goodness:
parameters.ForEach(parameter => doSomethingTo(parameter));
//Old stylz:
foreach (var parameter in parameters) {
doSomethingTo(parameter);
}
Bit nit-picky I know, but I noticed Daniel Cazzulino made the same observation:
"I added a ForEach extension method to IEnumerable. How come it's missing in .NET 3.5? :S"
So at least I'm not completely alone on this :-) Anyone else wonder about this?

4 comments:
I was searching for it just now.
Incredible.
I need to convert to List before using the ForEach.
I tried to add a ForEach a extension, but i cannot write it without the usage of the
foreach(var v in IEnum...)
So again is like returning to a List
:(
@gugo,
I'm not sure exactly what problem you are having getting the ForEach extension to work. Feel free to post some code or email me if you would like any clarification.
Regards,
David
Indeed, it's seems incredible to me they just forgot that feature. Do you know if there is any good reason behind, or do you believe it's really an omission?
Hi @Yann,
I really have no idea why it's not in there. I can't see any downsides for including it.
At least it's easy to add thanks to extension methods :)
Post a Comment