Lambda Expression using Foreach Clause [duplicate]

It’s perfectly possible to write a ForEach extension method for IEnumerable<T>.

I’m not really sure why it isn’t included as a built-in extension method:

  • Maybe because ForEach already existed on List<T> and Array prior to LINQ.
  • Maybe because it’s easy enough to use a foreach loop to iterate the sequence.
  • Maybe because it wasn’t felt to be functional/LINQy enough.
  • Maybe because it isn’t chainable. (It’s easy enough to make a chainable version that yields each item after performing an action, but that behaviour isn’t particularly intuitive.)

public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
{
    if (source == null) throw new ArgumentNullException("source");
    if (action == null) throw new ArgumentNullException("action");

    foreach (T item in source)
    {
        action(item);
    }
}

Leave a Comment