Welcome to MSDN Blogs Sign in | Join | Help

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?

Published Tuesday, August 19, 2008 8:46 AM by Glenn Block
Filed under: ,

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# discount furniture &raquo; ForEach, a simple but very useful extension method

# re: ForEach, a simple but very useful extension method

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.

Tuesday, August 19, 2008 4:22 AM by Krzysztof Koźmic

# re: ForEach, a simple but very useful extension method

It's there for List<T> since 2.0

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

Tuesday, August 19, 2008 8:20 AM by Miguel Madero

# re: ForEach, a simple but very useful extension method

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

Tuesday, August 19, 2008 9:27 AM by Mike Brown

# re: ForEach, a simple but very useful extension method

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

Wednesday, August 20, 2008 1:25 PM by Paul

# re: ForEach, a simple but very useful extension method

@Paul

Given:

List<string> titles = ....

You could:

foreach(string title in titles)

{

   title = title.ToUpperCase();

}

Or you could:

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

Thursday, August 21, 2008 1:16 PM by JamesCurran

# re: ForEach, a simple but very useful extension method

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.

Thursday, August 21, 2008 1:17 PM by JamesCurran

# Playing with Extension Methods - also explaining why they are dangerous!

Playing with Extension Methods - also explaining why they are dangerous!

Wednesday, October 01, 2008 7:51 PM by Techie.notepad

# ForEach

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

Sunday, February 01, 2009 2:41 AM by Kirill Osenkov

Leave a Comment

(required) 
required 
(required) 
 
Page view tracker