Reputation: 24422
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?
Upvotes: 29
Views: 29431
Reputation: 1361
If you need to change a property on MyClass using MyMethod, use the 'Pipe' method from Jon Skeet's morelinq library
items = items.Pipe<MyClass>(i => i.Text = i.UpdateText()).ToList()
The possibilities are endless! :)
Upvotes: 1
Reputation: 20246
Lists have a ForEach method. You could also create an IEnumerable extension method, but it kind of goes against the spirit of Linq.
Upvotes: 4
Reputation: 48127
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>
Upvotes: 56