Advanced LINQ (GroupBy, Join, Deferred Execution) Masterclass

โšก C# 12 & .NET 8 ๐ŸŸข Chapter 24 of 35 ๐Ÿ“‚ Phase 8: LINQ & Query Pipelines ๐Ÿ“… 2026 Edition
๐Ÿ“Œ Covered in this chapter: SelectMany ยท GroupBy ยท Join ยท Set Operations ยท Deferred Execution ยท Immediate Execution (ToList) ยท LINQ Performance

Welcome to Phase 8 (Chapter 24): C# Advanced LINQ, GroupBy, Join & Deferred Execution Masterclass! In this lesson, we explore complex query operations: SelectMany, GroupBy, Join, GroupJoin, Set operations (Distinct, Union, Intersect, Except), Aggregate, Deferred execution mechanics vs Immediate execution (ToList, ToArray), and LINQ performance optimization.

1Deferred Execution vs Immediate Execution

Most LINQ queries use **Deferred Execution** โ€” the query logic is NOT executed when defined, but rather when you iterate through the query results (e.g., via foreach). Methods like ToList() or ToArray() force **Immediate Execution**.

C# โ€” Deferred Execution Demonstration โ–ถ Run in Compiler
List<int> numbers = new() { 1, 2, 3 };

// Query defined (NOT executed yet!)
var query = numbers.Where(n => n > 1);

numbers.Add(4); // Modifying underlying collection AFTER query definition

// Execution happens NOW during foreach!
foreach (var item in query)
{
    Console.WriteLine(item); // Outputs: 2, 3, 4 (includes newly added 4!)
}
2GroupBy & Join Operations
C# โ€” GroupBy Example โ–ถ Run in Compiler
var students = new[]
{
    new { Name = "Ravi", Grade = "A" },
    new { Name = "Alice", Grade = "B" },
    new { Name = "Bob", Grade = "A" }
};

var groupedByGrade = students.GroupBy(s => s.Grade);

foreach (var group in groupedByGrade)
{
    Console.WriteLine($"Grade {group.Key} Students:");
    foreach (var student in group)
    {
        Console.WriteLine($" - {student.Name}");
    }
}
3Technical FAQs

Q1: What is the risk of multiple enumerations in LINQ?

Re-enumerating a deferred LINQ query multiple times executes the entire database or memory filtering operation again on each iteration. Call ToList() to cache results in memory if reading multiple times.