ToList()。ForEach在Linq [英] ToList().ForEach in Linq
问题描述
我是Linq的新人。
我想在foreach语句中设置两个值,如这样
I want to set two values in foreach statement like 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);
}
但是我想要这样的东西
employees.ToList().Foreach(collection.AddRange(emp.Departments),
emp.Departments.ToList().ForEach(u => u.SomeProperty = null))
推荐答案
ForEach
。阅读Lippert的foreachvsForEach
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
employees.All(p => {
collection.AddRange(p.Departments);
p.Departments.All(u => { u.SomeProperty = null; return true; } );
return true;
});
请注意,全部
表达式的结果是我们正在丢弃的 bool
值(我们仅使用它来循环所有元素)
Note that the result of the All
expression is a bool
value that we are discarding (we are using it only because it "cycles" all the elements)
我会重复一遍。您不应该使用 ForEach
来更改对象。 LINQ应以功能的方式使用(您可以创建新对象,但不能更改旧对象,也不能创建副作用)。你正在写的是创造如此多的无用的列表
只能获得两行代码...
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 useless List
only to gain two lines of code...
这篇关于ToList()。ForEach在Linq的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!