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: LINQ






December 29th, 2008 at 5:58 pm
really nice elegant solution. Thanks
May 27th, 2009 at 6:10 pm
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 .
May 28th, 2009 at 2:33 am
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.