[英]Set or Assign a value in a Nested generic collection using LinQ C#
I've a list of SelectedEmployees from list of Employees class in IEnumerable<Employee> SelectedEmployees
collection. 我有
IEnumerable<Employee> SelectedEmployees
集合中的Employees类列表中的SelectedEmployees列表。 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# 我如何才能仅将使用LinQ和C#的选定员工的
IsPhoneAssigned
值设置为true
public class Employee
{
IList<PhoneProperty> Phones {get; set;}
}
public class PhoneProperty
{
public bool IsPhoneAssigned { get; set; }
}
Linq is for querying, not for assignment. Linq用于查询,而不用于分配。 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.
但实际上我认为1选项是一种更具可读性和可维护性的方式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.