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))
This question is related to
c#
linq
entity-framework
Try this:
foreach (var dept in employees.SelectMany(e => e.Departments))
{
dept.SomeProperty = null;
collection.Add(dept);
}
You can use Array.ForEach()
Array.ForEach(employees, employee => {
Array.ForEach(employee.Departments, department => department.SomeProperty = null);
Collection.AddRange(employee.Departments);
});
you want this?
employees.ForEach(emp =>
{
collection.AddRange(emp.Departments.Where(dept => { dept.SomeProperty = null; return true; }));
});
employees.ToList().ForEach(
emp=>
{
collection.AddRange(emp.Departments);
emp.Departments.ToList().ForEach(u=>u.SomeProperty = null);
});
employees.ToList().Foreach(u=> { u.SomeProperty = null; u.OtherProperty = null; });
Notice that I used semicolons after each set statement
that is -->
u.SomeProperty = null;
u.OtherProperty = null;
I hope this will definitely solve your problem.
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.
Try with this combination of Lambda expressions:
employees.ToList().ForEach(emp =>
{
collection.AddRange(emp.Departments);
emp.Departments.ToList().ForEach(dept => dept.SomeProperty = null);
});
Source: Stackoverflow.com