LINQ Interview Question #55

What is the difference between Join and GroupJoin?

Joins, Grouping, Set & Quantifier Operators Mid-Level Intermediate

Quick Interview Answer

Join produces one result for each matching pair. If a customer has three orders, an inner Join can produce three rows for that customer.

Detailed Explanation

Join produces one result for each matching pair. If a customer has three orders, an inner Join can produce three rows for that customer.

GroupJoin produces one result per outer element and provides the matching inner elements as a sequence. This is useful when the grouped relationship itself is required.

Code Example

var flat = customers.Join(
    orders,
    c => c.Id,
    o => o.CustomerId,
    (c, o) => new { c.Name, o.Id });

var grouped = customers.GroupJoin(
    orders,
    c => c.Id,
    o => o.CustomerId,
    (c, os) => new { c.Name, Orders = os });