Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ToList().ForEach in Linq

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))    
like image 855
manav inder Avatar asked Oct 19 '11 05:10

manav inder


People also ask

How do you foreach in LINQ?

Convert a foreach loop to LINQ refactoringPlace your cursor in the foreach keyword. Press Ctrl+. to trigger the Quick Actions and Refactorings menu. Select Convert to LINQ or Convert to Linq (call form).

Why do we use ToList ()?

In LINQ, the ToList operator takes the element from the given source, and it returns a new List. So, in this case, input would be converted to type List.

Can I use foreach in IEnumerable C#?

In C#, it is not strictly necessary for a collection class to implement IEnumerable and IEnumerator in order to be compatible with foreach . As long as the class has the required GetEnumerator , MoveNext , Reset , and Current members, it will work with foreach .

Which is better foreach or LINQ?

Most of the times, LINQ will be a bit slower because it introduces overhead. Do not use LINQ if you care much about performance. Use LINQ because you want shorter better readable and maintainable code. So your experience is that LINQ is faster and makes code harder to read and to maintain?


1 Answers

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

like image 114
xanatos Avatar answered Oct 07 '22 19:10

xanatos