# IEnumerable 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);
}
}
}
Update 2008-07-17: An anonymous commenter left a great point about returning source after finishing the iteration instead of using a void method. This breaks the standard signature used by the Array and List<T> classes, but fits in nicely with the general approach used in the System.Linq.Enumerable extension methods, and lets you do LINQy method chaining.

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"