tags:

views:

122

answers:

3

Is there a way to call a method on every object in a List - e.g.

Instead of

List<MyClass> items = setup();

foreach (MyClass item in items)
   item.SomeMethod();

You could do something like

foreach(items).SomeMethod();

Anything built in, extension methods, or am I just being too damn lazy?

+8  A: 
items.ForEach(i => i.SomeMethod());
Tim Coker
Is this new in 4.0?
Rosarch
@Rosarch: Nope. http://msdn.microsoft.com/en-us/library/bwabdf9z.aspx note that coderush will suggest this as a change from foreach(var x in items) x.SomeMethod();
SnOrfus
@Brian Genisio ya i think i noticed/fixed that at the same time as your comment...
Tim Coker
+6  A: 

Yes, on List<T>, there is:

items.ForEach(item => item.SomeMethod())

The oddity is that this is only available on List<T>, not IList<T> or IEnumerable<T>

To fix this, I like to add the following extension method:

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

Then, you can use it on ANYTHING that implements IEnumerable<T>... not just List<T>

Brian Genisio
How did I miss .ForEach ... sums up my day today! Nice extension method.
Ryan
+2  A: 

Lists have a ForEach method. You could also create an IEnumerable extension method, but it kind of goes against the spirit of Linq.

R0MANARMY
Of course, as one of the commenters on that post demonstrated, sometimes there's no (tidy) substitute for ForEach. However, if it's just to call one or two methods on _every_ object in a container, using classic foreach really is the way to go.
Chris Charabaruk