Posted on 5/8/2008 8:17:34 PM by Justin Etheredge
List<T> has a method called ForEach that takes an Action<T> delegate, and I wanted one for IEnumerable. I also had someone ask about it in my previous post. It wasn't hard to write, but I figured I would throw it up here for future reference and also in case anyone needed help getting theirs working. If anyone notices anything I did that was dumb you can give me feedback as well. I believe I actually implemented something similar to this a while back, but anyways... without further ado...
public static void ForEach<T>(this IEnumerable<T> enumerable, Action<T> action)
{ if (enumerable == null)
throw new ArgumentNullException("enumerable");
if (action == null)
throw new ArgumentNullException("action");
foreach (T item in enumerable)
{ action(item);
}
}
Hope it helps.