Set multiple properties in a List<T> ForEach()?

Given a class:

class foo
{
    public string a = "";
    public int b = 0;
}

Then a generic list of them:

var list = new List<foo>(new []{new foo(), new foo()});

If I am to assign multiple properties inside the following List<T> ForEach() method, is there a simpler way to do it that below? Hopefully I'm being a bit thick.

// one property - easy peasy
list.ForEach(lambda => lambda.a="hello!");
// multiple properties - hmm
list.ForEach(lambda => new Action(delegate() { lambda.a = "hello!"; lambda.b = 99;}).Invoke());

Edit: Thought ForEach() was a LINQ extension method, when it's actually part of List<T> oops!


All you need to do is introduce some brackets so that your anonymous method can support multiple lines:

list.ForEach(i => { i.a = "hello!"; i.b = 99; });

Anonymous method is your friend

list.ForEach(item => 
              { 
                  item.a = "hello!"; 
                  item.b = 99; 
              }); 

MSDN:

  • Anonymous Methods (C# Programming Guide)

list.ForEach(lamba=>lambda.a="hello!"); 

Becomes

list.ForEach(item=>{
     item.a = "hello!";
     item.b = 99;
});

Of course you can also assign them when you create the list like :

var list = new List<foo>(new []{new foo(){a="hello!",b=99}, new foo(){a="hello2",b=88}});