C# 在 List<T> ForEach() 中设置多个属性?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9114748/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 06:01:58  来源:igfitidea点击:

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

c#linq

提问by maxp

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 multipleproperties inside the following List<T>ForEach()method, is there a simpler way to do it that below? Hopefully I'm being a bit thick.

如果我要在以下方法中分配多个属性,下面List<T>ForEach()是否有更简单的方法?希望我有点厚。

// 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!

编辑:以为ForEach()是 LINQ 扩展方法,但实际上它是List<T>oops的一部分!

采纳答案by Justin Niessner

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

回答by sll

Anonymous method is your friend

匿名方法是你的朋友

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

MSDN:

微软:

回答by Richard Friend

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

回答by Khodor

list.ForEach(i => i.DoStuff());
public void DoStuff(this foo lambda)
{
  lambda.a="hello!"; 
  lambda.b=99;
}

回答by Heinzi

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

老实说,这里真的没有必要使用 List.ForEach:

foreach (var item in list) { item.a="hello!"; item.b=99; }