Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generics - call a method on every object in a List<T>

Tags:

c#

generics

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?

like image 689
Ryan Avatar asked Jul 07 '10 19:07

Ryan


People also ask

How do I call a method in a list C#?

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#.

What is list T?

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.

What is generic list in C#?

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.


1 Answers

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>

like image 162
Brian Genisio Avatar answered Oct 07 '22 21:10

Brian Genisio