ToList(). Linq's ForEach

c# entity-framework linq

Question

Linq is new to me.

I want to use the following foreach statement to set two values:

This is my real code.

foreach (Employee emp in employees)
{
    foreach(Department dept in emp.Departments)
    {
        dept.SomeProperty = null;
    }
    collection.AddRange(emp.Departments);              
}

The above becomes this with some little reworking.

foreach (Employee emp in employees)
{
    emp.Departments.ToList().ForEach(u => u.SomeProperty = null))
    collection.AddRange(emp.Departments);              
}

However, I want something similar.

employees.ToList().Foreach(collection.AddRange(emp.Departments),
emp.Departments.ToList().ForEach(u => u.SomeProperty = null))
1
50
10/3/2016 3:58:55 PM

Accepted Answer

You must not utilizeForEach such that. Read "oeforeach" vs. "ForEach" by Lippert.

Create only useful things if you want to be harsh to yourself (and the world).List

employees.All(p => {
    collection.AddRange(p.Departments);
    p.Departments.All(u => { u.SomeProperty = null; return true; } );
    return true;
});

Take note that the outcome of theAll An expressionbool value that we are throwing away (we are using it only because it "cycles" all the elements)

Again, I say. You must not utilizeForEach to alter the things. Use of LINQ should be "functional" (you can build new objects but not alter existing ones or have side effects). And the writing you're doing is producing so many worthlessList only two more lines of code...

68
1/7/2020 10:53:38 AM

Popular Answer

This is an improper usage of ForEach, as xanatos pointed out.

If you're going to handle this using Linq, I recommend doing it as follows:

var departments = employees.SelectMany(x => x.Departments);
foreach (var item in departments)
{
    item.SomeProperty = null;
}
collection.AddRange(departments);

The Loop technique, on the other hand, is easier to understand and maintain.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow