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

  • Anonymous
    August 18, 2008
    PingBack from http://informationsfunnywallpaper.cn/?p=1189

  • Anonymous
    August 18, 2008
    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.

  • Anonymous
    August 19, 2008
    It's there for List<T> since 2.0 some of those methods should've been refactored down as IEnumerable<T> extensions

  • Anonymous
    August 19, 2008
    Was too lazy to do it myself so I just cheated and used Let ;)

  • Anonymous
    August 20, 2008
    I'm missing the point I guess - but why is this usefull over just using the foreach() w/o the extension?

  • Anonymous
    August 21, 2008
    @Paul Given: List<string> titles = .... You could: foreach(string title in titles) {    title = title.ToUpperCase(); } Or you could: titles.ForEach(t => t=t.ToUpperCase());

  • Anonymous
    August 21, 2008
    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.

  • Anonymous
    October 01, 2008
    Playing with Extension Methods - also explaining why they are dangerous!

  • Anonymous
    January 31, 2009
    In my recent post about coding styles one particular thing provoked the majority of feedback and discussions:

  • Anonymous
    September 03, 2009
    foreach(var t in titles) t = t.ToUpperCase(); titles.ForEach(t => t = t.ToUpperCase()); Not much difference...