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?
Using List<T>ForEach() Method. Alternatively, you can use the List<T>ForEach() function to call a specified action for each item in a list. Similar to the ForAll() method, this will not modify the source list. That's all about applying a function to each element in a list in C#.
The List<T> is a collection of strongly typed objects that can be accessed by index and having methods for sorting, searching, and modifying list. It is the generic version of the ArrayList that comes under System.
The Generic List<T> Class in C# is a collection class that is present in System. Collections. Generic namespace. This Generic List<T> Collection Class represents a strongly typed list of objects which can be accessed by using the index.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With