将linq Join转换为左连接

时间:2016-06-03 12:08:24

标签: linq join

我试图转换此查询

            userSummery = userSummery.Join(usersStatus, su => su.EmailAddress, us => us.EMail, (su, us) =>
                new UserSummary()
                {
                    Department = su.Department,
                    EmailAddress = su.EmailAddress,
                    FirstName = su.FirstName,
                    LastName = su.LastName,
                    FullName = su.FullName,
                    Id = su.Id,
                    PhoneNumber = su.PhoneNumber,
                    RmgUserId = su.RmgUserId,
                    IsActive = su.IsActive,
                    UserName = su.UserName,
                    Status = us.Status
                }).ToList();
            return userSummery;

返回所有su,即使是那些没有匹配我们的人。

我已经查看了How do you perform a left outer join using linq extension methods,但无法弄清楚如何使其适用于稍微复杂的案例。

1 个答案:

答案 0 :(得分:2)

试试这个:

var userSummery = (from su in userSummery
                  join us in usersStatus
                  on su.EmailAddress equals us.EMail into sub 
                  from s in sub.DefaultIfEmpty()
                  select new
                  {
                      su,
                      status = s == null ? 0 : s.Status//or other default value instead of 0
                  }).ToList()
                  .Select(x => { x.su.Status = x.status; return x.su; }).ToList();