Friday 1 May 2009

Perform an Action for each value in a Collection

I really don't know why there is no ForEach method in LINQ. If you want to perform an action on every item in a collection you have to use the TAccumulate Aggregate<TSource, TAccumulate>(TAccumulate, Func<TAccumulate, TSource TAccumulate>) method in order to avoid deferred execution, but calling it with a simple action leads to unnecessary ugly and hard to understand code.

To solve this issue just create a new extension method that wraps the call Aggregate call:

public static class IEnumerableExtensions
{
public static void ForEach<TSource>(this IEnumerable<TSource> source, Action<TSource> action)
{
source.Aggregate<TSource, object>(null, (dummy, item) => { action(item); return null; });
}
}

No comments:

Post a Comment