Lesson 23/31

Tutorials LINQ Mastery

GroupJoin: Creating hierarchical results

On this page

The One-to-Many Join

Standard Join gives you a flat list. GroupJoin gives you a hierarchical list, where each outer item is paired with a collection of its matching inner items.

1. Hierarchy Pattern

Think of a list of Departments and its Employees. A GroupJoin will give you a sequence where each Department object contains a list of its Employees. This is exactly how we usually think about data in the real world.


var query = departments.GroupJoin(
    employees,
    dept => dept.Id,
    emp => emp.DeptId,
    (dept, empGroup) => new {
        DepartmentName = dept.Name,
        Staff = empGroup // staff is an IEnumerable<Employee>
    }
);
    

2. Relationship with SQL

In SQL, there is no direct equivalent to GroupJoin because SQL only returns flat sets. EF Core translates this into a LEFT OUTER JOIN and then reshapes the data into objects on the client side.

3. Architect Insight

Q: "When should I use GroupJoin instead of GroupBy?"

Architect Answer: "Use **GroupJoin** if you already have two separate lists. Use **GroupBy** if you have ONE list that you want to split into categories. GroupJoin is essentially a 'Join then GroupBy' in one high-performance operation."

Questions on this lesson 0

Sign in to ask a question or upvote helpful answers.

No questions yet — be the first to ask!

LINQ Mastery
Course syllabus
General
1. Core Foundations
2. Filtering & Transformation
3. Aggregation & Quantifiers
4. Ordering & Partitioning
5. Sets & Lookups
6. Join & Grouping
7. Advanced Providers & Parallelism
8. Real-world Performance & Patterns
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details