LINQ Interview Question #141
How can LINQ implement a full outer join?
Advanced LINQ, Practical Problems & Senior Interview Scenarios Senior Advanced
Quick Interview Answer
LINQ does not have one classic universal FullOuterJoin operator across all LINQ scenarios. For in-memory data, one approach is to combine a left-side result with unmatched elements from the right side.
Detailed Explanation
LINQ does not have one classic universal FullOuterJoin operator across all LINQ scenarios. For in-memory data, one approach is to combine a left-side result with unmatched elements from the right side.
For database IQueryable queries, the best implementation depends on provider translation capabilities and database support. Complex outer-join requirements should be designed with the generated SQL in mind.
Code Example
var left = leftItems
.GroupJoin(rightItems,
l => l.Id,
r => r.Id,
(l, rs) => new { l, rs })
.SelectMany(
x => x.rs.DefaultIfEmpty(),
(x, r) => new { Left = x.l, Right = r });
var leftIds = leftItems.Select(x => x.Id).ToHashSet();
var rightOnly = rightItems
.Where(r => !leftIds.Contains(r.Id))
.Select(r => new { Left = (Item?)null, Right = r });
var full = left.Concat(rightOnly);