gpt4 book ai didi

.net - 在 foreach 循环声明中使用 LINQ

转载 作者:行者123 更新时间:2023-12-04 17:50:48 24 4
gpt4 key购买 nike

在 foreach 循环声明中直接声明 LINQ 是不好的做法吗?在性能或细微的行为差异方面。

例如:

foreach (string name in persons.Select(x => x.name))
{
//Do something with name
}

最佳答案

不。没有错。只要 Linq 表达式简短且易于阅读,我认为这是最重要的。你的例子是一个很好的例子,说明何时应该以这种方式使用此类查询。

但是,如果它比这长得多,或者如果您使用查询语法,我建议将其分成两行,如下所示:

var names = persons.Select(x => x.name).Blah().Blah().Blah();
foreach (string name in names)
{
//Do something with name
}

或者
var names = 
from x in persons
select x.name;
foreach (string name in names)
{
//Do something with name
}

关于.net - 在 foreach 循环声明中使用 LINQ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16888940/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com