ForEach method in every IEnumerable

ForEach method is wonderful, unfortunately is a member of List<T>.
What if you want to have this method in all IEnumerable<T>? well, this extension method can help.

public static void ForEach<T>(this IEnumerable<T> collection, Action<T> action)
{
    foreach (var item in collection){ action(item); }            
}

With this method you can do the following:

"a,b,c,d".Split(',').ForEach(Console.WriteLine);

Note: This article was titled “ForEach method in every ICollection<T>”, but as suggested by Fabio Maulo can be better with IEnumerable<T>, so I’ve downgraded the type of the parameter.


blog comments powered by Disqus
  • Categories

  • Archives