LINQ ForEach for IEnumerableltTgt

It seems to me strange that LINQ does not define an extension method ForEach to apply some Action<T> on an IEnumerable<T>. Array and List both have ForEach() method, and IEnumerable really miss it a lot, but fortunately implementing it is a matter of few lines of code.

1
2
3
4
5
6
7
public static IEnumerable<T> ForEach<T>(
    this IEnumerable<T> source, 
    Action<T> act)
{
    foreach (T element in source) act(element);
    return source;
}

I decided to make the ForEach<T> return the original list, so I can use with chaining in fluent interface, but you can also make it return void, thus restricting its use only at the end of a linq chain.

Alk.

Tags: LINQ