Linq 中的 ToList().ForEach
我是 Linq 新手。
我想在 foreach
语句中设置两个值,如下所示
我的实际代码是这样的
foreach (Employee emp in employees)
{
foreach(Department dept in emp.Departments)
{
dept.SomeProperty = null;
}
collection.AddRange(emp.Departments);
}
一点重构将上面的内容变成这样
foreach (Employee emp in employees)
{
emp.Departments.ToList().ForEach(u => u.SomeProperty = null))
collection.AddRange(emp.Departments);
}
但我想要这样的东西
employees.ToList().Foreach(collection.AddRange(emp.Departments),
emp.Departments.ToList().ForEach(u => u.SomeProperty = null))
I am new to Linq.
I want to set two values in foreach
statement like this
My actual code is this
foreach (Employee emp in employees)
{
foreach(Department dept in emp.Departments)
{
dept.SomeProperty = null;
}
collection.AddRange(emp.Departments);
}
Little refactoring turns the above into this
foreach (Employee emp in employees)
{
emp.Departments.ToList().ForEach(u => u.SomeProperty = null))
collection.AddRange(emp.Departments);
}
But I want something like this
employees.ToList().Foreach(collection.AddRange(emp.Departments),
emp.Departments.ToList().ForEach(u => u.SomeProperty = null))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
您不应该以这种方式使用
ForEach
。阅读 Lippert 的“foreach”与“ForEach”如果你想对自己(和世界)残酷一点,至少不要创建无用的
List
请注意,
All
表达式的结果是我们正在丢弃的bool
值(我们使用它只是因为它“循环”所有元素)我将重复一遍。您不应该使用
ForEach
来更改对象。 LINQ 应该以“函数式”方式使用(您可以创建新对象,但不能更改旧对象,也不能产生副作用)。而你所写的是创建这么多无用的List
只是为了获得两行代码......You shouldn't use
ForEach
in that way. Read Lippert's “foreach” vs “ForEach”If you want to be cruel with yourself (and the world), at least don't create useless
List
Note that the result of the
All
expression is abool
value that we are discarding (we are using it only because it "cycles" all the elements)I'll repeat. You shouldn't use
ForEach
to change objects. LINQ should be used in a "functional" way (you can create new objects but you can't change old objects nor you can create side-effects). And what you are writing is creating so many uselessList
only to gain two lines of code...正如 xanatos 所说,这是对 ForEach 的误用。
如果您打算使用 linq 来处理此问题,我会这样做:
但是,循环方法更具可读性,因此更易于维护。
As xanatos said, this is a misuse of ForEach.
If you are going to use linq to handle this, I would do it like this:
However, the Loop approach is more readable and therefore more maintainable.
试试这个:
Try this:
请注意,我在每个 set 语句后使用了分号
那就是 -->
我希望这一定能解决您的问题。
Notice that I used semicolons after each set statement
that is -->
I hope this will definitely solve your problem.
您可以使用Array.ForEach()
You can use
Array.ForEach()
你想要这个吗?
you want this?
尝试使用以下 Lambda 表达式组合:
Try with this combination of Lambda expressions: