ToList().ForEach in Linq
employees.ToList().ForEach(
emp=>
{
collection.AddRange(emp.Departments);
emp.Departments.ToList().ForEach(u=>u.SomeProperty = null);
});
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:
var departments = employees.SelectMany(x => x.Departments);
foreach (var item in departments)
{
item.SomeProperty = null;
}
collection.AddRange(departments);
However, the Loop approach is more readable and therefore more maintainable.
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...