Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute method for each object in generic list using lambda

Tags:

c#

lambda

linq

I'm still new to lambdas and find it hard to find out specific features for it, but is it possible to execute a method for each object in a generic list? Similar to how the ConvertAll works, but instead of converting, actually calling a method.

public class Mouse()
{
    public void Squeak()
    {
    }
}

List<Mouse> mice = new List<Mouse>();

mice.Add(new Mouse());
mice.Add(new Mouse());

How do you call the method Squeak for each mouse?

mice.???(m => m.Squeak());
like image 593
Levitikon Avatar asked Oct 14 '11 15:10

Levitikon


2 Answers

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

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

PS: What is fun that answer is in your question:

How do you call the method Squeak for each mouse?

like image 127
sll Avatar answered Oct 13 '22 00:10

sll


Please don't use List<T>.ForEach. It looks like a sequence operator. Sequence operators shouldn't have side effects. You're using something that looks like a sequence operator solely for its side effects. Instead, just use a plain-old boring loop:

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

Eric Lippert has a fabulous article related to this topic: foreach vs. ForEach.

like image 32
jason Avatar answered Oct 13 '22 00:10

jason