LINQ - Full Outer Join

后端 未结 16 1561
既然无缘
既然无缘 2020-11-21 22:45

I have a list of people\'s ID and their first name, and a list of people\'s ID and their surname. Some people don\'t have a first name and some don\'t have a surname; I\'d l

16条回答
  •  逝去的感伤
    2020-11-21 23:04

    I don't know if this covers all cases, logically it seems correct. The idea is to take a left outer join and right outer join then take the union of the results.

    var firstNames = new[]
    {
        new { ID = 1, Name = "John" },
        new { ID = 2, Name = "Sue" },
    };
    var lastNames = new[]
    {
        new { ID = 1, Name = "Doe" },
        new { ID = 3, Name = "Smith" },
    };
    var leftOuterJoin =
        from first in firstNames
        join last in lastNames on first.ID equals last.ID into temp
        from last in temp.DefaultIfEmpty()
        select new
        {
            first.ID,
            FirstName = first.Name,
            LastName = last?.Name,
        };
    var rightOuterJoin =
        from last in lastNames
        join first in firstNames on last.ID equals first.ID into temp
        from first in temp.DefaultIfEmpty()
        select new
        {
            last.ID,
            FirstName = first?.Name,
            LastName = last.Name,
        };
    var fullOuterJoin = leftOuterJoin.Union(rightOuterJoin);
    

    This works as written since it is in LINQ to Objects. If LINQ to SQL or other, the query processor might not support safe navigation or other operations. You'd have to use the conditional operator to conditionally get the values.

    i.e.,

    var leftOuterJoin =
        from first in firstNames
        join last in lastNames on first.ID equals last.ID into temp
        from last in temp.DefaultIfEmpty()
        select new
        {
            first.ID,
            FirstName = first.Name,
            LastName = last != null ? last.Name : default,
        };
    

提交回复
热议问题