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