LINQ查询中的左外连接

时间:2013-01-29 05:21:23

标签: c# linq

  

可能重复:
  LEFT OUTER JOIN in LINQ

如何使用左外连接进行LINQ查询?

2 个答案:

答案 0 :(得分:9)

您可以使用Enumerable.DefaultIfEmpty方法进行左外连接。

您可能会看到:How to: Perform Left Outer Joins (C# Programming Guide) - MSDN

请考虑MSDN中的以下示例,

class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

class Pet
{
    public string Name { get; set; }
    public Person Owner { get; set; }
}

左外连接查询可以是:

var query = from person in people
            join pet in pets on person equals pet.Owner into gj
            from subpet in gj.DefaultIfEmpty()
            select new { person.FirstName, PetName = (subpet == null ? String.Empty : subpet.Name) };

答案 1 :(得分:4)

 var query = (from t1 in Context.Table1
              join t2temp in Context.Table2 on t1.Id equals t2.Id into tempJoin
              from t2 in tempJoin.DefaultIfEmpty()
              select ...);