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))
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).
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.
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 .
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?
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With