Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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))
  
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
403 views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...