6

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());

2 Answers 2

6

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?

Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.