Set multiple properties in a List ForEach()?

后端 未结 5 913
感情败类
感情败类 2021-01-30 05:04

Given a class:

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

Then a generic list of them:

var list = new List         


        
相关标签:
5条回答
  • 2021-01-30 05:16

    Honestly, there's really no need to use List.ForEach here:

    foreach (var item in list) { item.a="hello!"; item.b=99; }
    
    0 讨论(0)
  • 2021-01-30 05:22

    Anonymous method is your friend

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

    MSDN:

    • Anonymous Methods (C# Programming Guide)
    0 讨论(0)
  • 2021-01-30 05:28
    list.ForEach(i => i.DoStuff());
    public void DoStuff(this foo lambda)
    {
      lambda.a="hello!"; 
      lambda.b=99;
    }
    
    0 讨论(0)
  • 2021-01-30 05:29
    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}}); 
    
    0 讨论(0)
  • 2021-01-30 05:34

    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; });
    
    0 讨论(0)
提交回复
热议问题