Back to results for “LINQ”
C# › LINQ

How would you write an efficient LINQ query combining Join() with GroupBy() to replicate a SQL-style LEFT OUTER JOIN with aggregation?

Advanced

Answer

Use GroupJoin() (which pairs each element from the outer sequence with a GROUP of matching elements from the inner sequence, including an EMPTY group for no matches — mimicking a LEFT OUTER JOIN), then flatten and aggregate the grouped results as needed, unlike a regular Join() which behaves like an INNER JOIN and drops unmatched outer elements entirely.
var results = customers.GroupJoin(
    orders,
    customer => customer.Id,
    order => order.CustomerId,
    (customer, customerOrders) => new {
      customer.Name,
      OrderCount = customerOrders.Count() // 0 for customers with no matching orders, unlike an inner Join
    });
Real-world example Generating a report showing EVERY customer's order count, including customers with ZERO orders, mirroring a SQL LEFT JOIN with COUNT.

Common follow-ups: How does regular Join() (INNER JOIN semantics) behave differently for customers with no matching orders at all?