José F. Romaniello

Las aventuras y desventuras de un codificador.

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:


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.

| More

2 comentarios:

why not as extension of IEnumerable<T> ?

Yes, is better.

Publicar un comentario