LINQ在执行左外连接时更新所选对象

时间:2016-12-08 02:01:18

标签: c# linq

在下面的代码中,我有一个Employee对象的集合。我必须检查员工是否是InOrg。为此,我使用InOrgCatalog表进行左连接并返回一个匿名对象。我已经有了InOrg属性 在我的Employee对象中,因此我想要返回一个更新InOrg属性的Employee对象,而不是返回一个匿名对象。我在查询中要做些什么改变才能实现呢?

List<Employee> employees = new List<Employee>
                {
                    new Employee {  EmployeeId = 1, EmployeeName = "Aaron" , Alias = "AWERAS", InOrg = false},
                    new Employee {  EmployeeId = 2, EmployeeName = "asdfsdf" , Alias = "HJKHJK", InOrg = false},
                    new Employee {  EmployeeId = 3, EmployeeName = "qwerwe" , Alias = "NMUIYUI", InOrg = false},
                    new Employee {  EmployeeId = 4, EmployeeName = "zcvcx" , Alias = "PIOUKJ", InOrg = false},
                };

using (var context = new MyDbContext())
       {
            var result = (from employee in employees
                          join catalog in context.InOrgCatalogs on new { Alias = employee.Alias,  Active = true } equals 
                          new { Alias = catalog.Alias,  Active = catalog.Active }
                          into ps
                          from p in ps.DefaultIfEmpty()
                          select  new { Employee = employee , InOrg = !(p == null)}).ToList();                
       }

2 个答案:

答案 0 :(得分:0)

在我看来,你需要选择一个新的Employeee对象而不是一个匿名对象。然后,您可以根据需要更新属性:

using (var context = new MyDbContext())
{
    var result = (from Employee employee in employees
                  join catalog in context.InOrgCatalogs on new { Alias = employee.Alias, Active = true } equals
                  new { Alias = catalog.Alias, Active = catalog.Active }
                  into ps
                  from p in ps.DefaultIfEmpty()
                  select new Employee { EmployeeId = employee.EmployeeId,EmployeeName = employee.EmployeeName, Alias = employee.Alias, InOrg = !(p == null) }).ToList();
}

答案 1 :(得分:0)

此外,您可以使用StringEscapeUtils关键字和双重分配技巧:

let