Execute a method for each object in the general list using lambda

I'm still new to lambdas and don't know how to do this, but is it possible to execute a method for each object in the general list? Similar to how ConvertAll works, but instead of converting, actually calling the method.

public class Mouse() { public void Squeak() { } } List<Mouse> mice = new List<Mouse>(); mice.Add(new Mouse()); mice.Add(new Mouse()); 

What do you call the Squeak method for each mouse?

 mice.???(m => m.Squeak()); 
+6
source share
2 answers

You can do this using the List<T>.ForEach() method ( see MSDN ):

 mice.ForEach(m => m.Squeak()); 

PS: Interestingly, the answer is in your question:

What do you call the Squeak method for each mouse?

+4
source

Please do not use List<T>.ForEach . It looks like a sequence operator. Sequence operators should not have side effects. You use what looks like a sequence operator solely for its side effects. Instead, just use the old raster loop:

 foreach(var mouse in mice) { mouse.Squeak(); } 

Eric Lippert has an amazing article related to this topic: foreach vs. foreach .

+3
source

Source: https://habr.com/ru/post/899309/


All Articles