alkampfer on August 13th, 2008

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.

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.

kick it on DotNetKicks.com

Tags:



kick it on DotNetKicks.com

Leave a Reply