了ToList()的ForEach Linq中 [英] ToList().ForEach in Linq

查看:606
本文介绍了了ToList()的ForEach Linq中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的LINQ。

我要设置foreach语句两个值这样的

我的实际code是该

 的foreach(在员工员工EMP)
 {
  的foreach(在emp.Departments部部)
   {
     dept.SomeProperty = NULL;
    }
    collection.AddRange(emp.Departments);
 }

小重构轮流到上述这种

 的foreach(在员工员工EMP)
 {
  。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 。阅读利珀特的的foreachVS的ForEach

如果你想成为残酷与自己(和世界),至少不要创建无用列表

  employees.All(P => {
    collection.AddRange(p.Departments);
    p.Departments.All(U => {u.SomeProperty = NULL;返回true;});
    返回true;
});

需要注意的是结果的所有前pression是我们丢弃布尔值(我们使用它只是因为它循环的所有元素)

我会重复。你不应该使用的ForEach 修改对象。 LINQ应以功能性的方式(可以创建新的对象,但你不能改变旧的对象,也可以创建副作用)使用。和你正在编写创造那么多没用的列表只获得两行code ...

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

解决方案

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

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)

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆