cody said:
There is absolutely no reason why there is a ForEach() method on
ArrayList but not on IEnumerable.
Well, my point is that there shouldn't have been a .ForEach() method on
*anything*. If two ways are provided to do the same thing, there should be
clear situational advantages in using one or the other. .ForEach() versus
the foreach statement definitely doesn't qualify -- foreach can do
everything .ForEach() can and more. Enumeration is such a fundamental part
of the framework that it seems like whoever added .ForEach() wasn't really
thinking about the usefulness, just adding something because they could.
List<T>.ForEach() now returns void, it would be cool if it returned
Enumerable<T> so one could nicely chain lots of stuff or maybe we could
use ForEach() in LINQ queries for pre transforming data before using it.
But that already exists -- it's called .Select(), and the idea is that it
*doesn't* change the objects themselves but returns the result of some
function applied to them. Of course, there's nothing to prevent you from
breaking the rules and modifying the objects in the .Select() delegate, but
introducing side effects like this makes code much harder to understand (and
also not thread-safe, but that's another topic).
If you really want an in-place transformational approach, that's easy
enough, but you'd have to define it on IList<T>, not IEnumerable<T>,
otherwise you couldn't replace the elements:
public static IList<T> Transform<T>(this IList<T> list, Func<T, T>
transform) {
for (int i = 0; i != list.Count; ++i) {
list
= transform(list);
}
return list;
}
Now even if your method isn't changing the object identity, you could still
use it:
myList.Where(e => e.Import).Transform(e => { e.Method.Invoke(); return e; });
And if you do this often you could provide another method, and this one
could work on IEnumerable:
public static IEnumerable<T> Apply<T>(this IEnumerable<T> sequence,
Action<T> action) {
foreach (T t in sequence) action(t);
return sequence;
}
So now you can chain to your heart's content:
myList.Where(e => e.Import).Select(e => e.Method).Apply(m =>
m.Invoke()).Apply(m => m.Invoke());
This approach is limited in that, unlike .Select(), it can't produce
sequences with a different type. And while you can chain, it's a little
pointless, because you could just fold all the transformations into one
delegate that executes them sequentially. Or, indeed, use foreach:
foreach (var m in from e in myList where e.Import select e.Method) {
m.Invoke();
m.Invoke();
}
I know which one I prefer. This is C#, not JQuery. 
But I think that adding ForEach() to the framework now would be a
breaking change as the call it, since there is already an implementation
in class List
Actually, no, thanks to the rules for extension methods. Instance methods
always take precedence over extension methods, so List<T>.ForEeach() would
not clash with Enumerable.ForEach().