linq / lambda 中的多行 foreach 循环
我正在寻找一种方法来更改以下代码:
foreach (Contact _contact in contacts)
{
_contact.ID = 0;
_contact.GroupID = 0;
_contact.CompanyID = 0;
}
我想使用 LINQ / lambda 将其更改为类似于以下内容的内容:
contacts.ForEach(c => c.ID = 0; c.GroupID = 0; c.CompanyID = 0);
但这不起作用。除了编写一个函数在一行中执行此操作之外,还有什么方法可以在 linq foreach 中执行多行操作吗?
I am looking for a way to change the following code:
foreach (Contact _contact in contacts)
{
_contact.ID = 0;
_contact.GroupID = 0;
_contact.CompanyID = 0;
}
I would like to change this using LINQ / lambda into something similar to:
contacts.ForEach(c => c.ID = 0; c.GroupID = 0; c.CompanyID = 0);
However that doesn't work. Is there any way to do multi-line in a linq foreach other than by writing a function to do this in one line?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它与 LINQ 本身没有任何关系;它只是一个用 lambda 语法编写的简单匿名方法,传递给 List.ForEach 函数(该函数从 2.0 开始,在 LINQ 之前就存在)。
It doesn't have anything to do with LINQ per se; it's just a simple anonymous method written in lambda syntax passed to the
List<T>.ForEach
function (which existed since 2.0, before LINQ).LINQ 代表语言集成查询 - 这意味着它用于查询 - 即提取序列或将序列转换为新集合,而不是操作原始序列。
ForEach
方法挂起List
是 foreach 的便捷快捷方式;没什么特别的。LINQ stands for Language Integrated Query - which means it is intended for querying - i.e. extracting or transforming a sequence into a new set, not manipulating the original.
The
ForEach
method hangs offList<T>
and is a convenience shortcut to foreach; nothing special.