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.

Tags:



kick it on DotNetKicks.com

3 Responses to “LINQ ForEach for IEnumerable<T>”

  1. really nice elegant solution. Thanks

  2. Alk,

    I think there is a reason Linq leaves this method out of the framework. Checkout John Skeet’s comments on the subject, http://stackoverflow.com/quest.....enumerable .

  3. Yes, you are right. Quite always there are reason for everything, I must admit that the reason you point up in the link is really reasonable. Sith a similar ForEach we have a LINQ operator with side effect, and this can violate the principle of least surprise.

    Thanks for the link.

    Alk.

Leave a Reply