Linq - 带点符号的左外连接

时间:2011-03-30 14:44:00

标签: c# linq linq-to-entities

如何使用点表示法在linq中执行左外连接?

这是查询表达式:

var query = from u in db.Users
            join d in db.Defects on u.userID equals d.userID into defectsGroup
            from d in defectsGroup.DefaultIfEmpty()
            select new { u, d };

这是我试过的:

var query2 = db.Users.GroupJoin(db.Defects.DefaultIfEmpty(), 
                u => u.userID, 
                d => d.userID, 
                (user, defect) => new { user, defect });

但缺陷显示为IEnumerable<Defect>,而不仅仅是Defect。我也尝试过:

var query2 = db.Users.GroupJoin(db.Defects, 
                u => u.userID, 
                d => d.userID, 
                (user, defect) => new { user, defect.DefaultIfEmpty() });

这根本就没有编译。所有在线示例似乎都使用(更清晰的)查询语法。

1 个答案:

答案 0 :(得分:25)

我想你想要这个:

var query2 = db.Users.GroupJoin(db.Defects,
                                u => u.userId,
                                d => d.userID,
                                (u, defectsGroup) => new { u, defectsGroup})
                     .SelectMany(z => z.defectsGroup.DefaultIfEmpty(),
                                 (z, d) => new { z.u, d });

有关详细信息,请参阅我的Edulinq blog post on query expressions