I've a list of SelectedEmployees from list of Employees class in IEnumerable<Employee> SelectedEmployees
collection. Again I've nested generic collection as below code. How can i set IsPhoneAssigned
value to true
for only selected employees using LinQ with C#
public class Employee
{
IList<PhoneProperty> Phones {get; set;}
}
public class PhoneProperty
{
public bool IsPhoneAssigned { get; set; }
}
Linq is for querying, not for assignment. Thus, your implementation can be split into two parts:
Something like this:
var query = SelectedEmployees.Where(x => myCondition(x));
foreach (var q in query)
foreach (var p in q.Phones)
p.IsPhoneAssigned = true;
var employeesList; // this is your list from context
foreach(var emp in employeesList) // iterate and change all phones
{
foreach(var ph in emp.Phones)
ph.IsPhoneAssigned = true;
}
_context.SubmitChanges(); // save changes to context
I find another elegant way to solve your problem:
var changedCollection = _context.SelectedEmployees.Select(x =>
{
x.Phones.Select(y =>
{
y.IsPhoneAssigned = true;
return y;
})
}).ToList();
_context.SubmitChanges();
Here you creating anonymouse function, that changes property of your object and return it with changed property. But actually i think 1 option is a way more readable and maintainable.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.