ForEach, a simple but very useful extension method


This evening I was writing some code (Yay!) for an Xml based MEF catalog I am prototyping. I came across the need to invoke a set of methods on an IEnumerable<T> that was returned from a LINQ to XML query. Unfortunately no such animal exists on IEnumerable.

It took me < 5 mins to write this

   1: public static class IEnumerableUtils
   2: {
   3:       public static void ForEach<T>(this IEnumerable<T> collection, Action<T> action)
   4:       {
   5:         foreach(T item in collection)
   6:           action(item);
   7:       }
   8: }

Any questions?

Comments (10)

  1. You’re not checking for nulls :)

    Other than that – similar method has been on my Utils.dll library for a long time now. It should have been in the framework in the first place.

  2. Miguel Madero says:

    It’s there for List<T> since 2.0

    some of those methods should’ve been refactored down as IEnumerable<T> extensions

  3. Mike Brown says:

    Was too lazy to do it myself so I just cheated and used Let 😉

  4. Paul says:

    I’m missing the point I guess – but why is this usefull over just using the foreach() w/o the extension?

  5. JamesCurran says:

    @Paul

    Given:

    List<string> titles = ….

    You could:

    foreach(string title in titles)

    {

       title = title.ToUpperCase();

    }

    Or you could:

    titles.ForEach(t => t=t.ToUpperCase());

  6. JamesCurran says:

    I’d suggest making it:

    public static IEnumerable<T> ForEach<T>(this IEnumerable<T> collection, Action<T> action)

    {…

     return collection;

    }

    so you could chain them.

  7. Playing with Extension Methods – also explaining why they are dangerous!

  8. In my recent post about coding styles one particular thing provoked the majority of feedback and discussions:

  9. Magnus says:

    foreach(var t in titles) t = t.ToUpperCase();

    titles.ForEach(t => t = t.ToUpperCase());

    Not much difference…