Tutorials / Advanced C# and .NET / LINQ in depth: deferred execution, grouping and joins

LINQ in depth: deferred execution, grouping and joins

15 min read csharp
Course contents (16 lessons)
  1. The type system
  2. Records, structs and value equality
  3. Interfaces and abstract classes
  4. Generics and constraints
  5. Delegates, events and lambdas
  6. Querying and matching data
  7. LINQ in depth: deferred execution, grouping and joins
  8. IEnumerable versus IQueryable
  9. Pattern matching in modern C#
  10. Async and await: how Task really works
  11. Async patterns: cancellation, timeouts and async streams
  12. Application structure
  13. Dependency injection and service lifetimes
  14. Configuration, options and logging
  15. Data and web
  16. Entity Framework Core basics: DbContext, migrations and queries
  17. Building a minimal API with ASP.NET Core
  18. Unit testing with xunit
  19. Performance and the final project
  20. Performance basics: Span of T and fewer allocations
  21. Final project: a notes API with EF Core, DI and logging

What LINQ really is

LINQ stands for Language Integrated Query. It is a set of extension methods, defined in System.Linq, that work on anything implementing IEnumerable<T>. Each method takes a sequence and returns a new sequence or a single result. Once you can read a chain of them like a sentence, you will write far less looping code.

The examples below use a small set of orders and customers so you can run everything and see the results.

var customers = new List<Customer>
{
    new(1, "Ayesha", "Lahore"),
    new(2, "Bilal", "Karachi"),
    new(3, "Chand", "Lahore"),
    new(4, "Dua", "Islamabad")
};

var orders = new List<Order>
{
    new(100, 1, 2500m, "Books"),
    new(101, 1, 900m, "Stationery"),
    new(102, 2, 15000m, "Electronics"),
    new(103, 3, 400m, "Books"),
    new(104, 3, 7200m, "Electronics"),
    new(105, 1, 3100m, "Electronics")
};

// Filter, sort, project
var big = orders
    .Where(o => o.Total >= 2000m)
    .OrderByDescending(o => o.Total)
    .Select(o => $"#{o.Id}: {o.Total:N0}");
Console.WriteLine(string.Join(" | ", big));

// Group and aggregate
var byCategory = orders
    .GroupBy(o => o.Category)
    .Select(g => new { Category = g.Key, Count = g.Count(), Sum = g.Sum(o => o.Total) })
    .OrderByDescending(x => x.Sum);
foreach (var row in byCategory)
{
    Console.WriteLine($"{row.Category,-12} {row.Count} orders, {row.Sum:N0}");
}

// Join: customer name with their spending
var spending = customers
    .GroupJoin(orders, c => c.Id, o => o.CustomerId,
        (c, os) => new { c.Name, c.City, Spent = os.Sum(o => o.Total) })
    .OrderByDescending(x => x.Spent);
foreach (var s in spending)
{
    Console.WriteLine($"{s.Name,-8} {s.City,-10} {s.Spent,8:N0}");
}

// SelectMany flattens
var tags = new[] { "a,b", "b,c", "d" }
    .SelectMany(t => t.Split(','))
    .Distinct();
Console.WriteLine(string.Join("", tags));

// Single value queries
Console.WriteLine(orders.Any(o => o.Total > 10000m));
Console.WriteLine(orders.All(o => o.Total > 100m));
Console.WriteLine(orders.Max(o => o.Total));
Console.WriteLine(orders.MaxBy(o => o.Total)!.Id);
Console.WriteLine(customers.FirstOrDefault(c => c.City == "Multan")?.Name ?? "nobody");

// Deferred execution
var numbers = new List<int> { 1, 2, 3 };
var query = numbers.Where(n => n > 1);     // nothing runs yet
numbers.Add(4);
Console.WriteLine(string.Join(",", query)); // 2,3,4 - runs now
var snapshot = numbers.Where(n => n > 1).ToList();  // runs now, result frozen
numbers.Add(5);
Console.WriteLine(snapshot.Count);          // 3

// Paging
var page2 = orders.OrderBy(o => o.Id).Skip(2).Take(2);
Console.WriteLine(string.Join(",", page2.Select(o => o.Id)));

record Customer(int Id, string Name, string City);
record Order(int Id, int CustomerId, decimal Total, string Category);

Walking through it

The first query reads naturally: keep orders of 2000 or more, sort by total from high to low, and make a line of text for each. Notice that each step passes its output to the next. The lambdas, like o => o.Total >= 2000m, are the delegates from the previous lesson.

GroupBy splits a sequence into groups that share a key. Each group is itself a sequence, and it has a Key property. Here we count and sum inside each group, and then project to an anonymous type, which is a small object with no name that exists only inside this method.

I used GroupJoin for the customer spending. It pairs every customer with the list of their orders, and importantly it keeps customers who have none. Dua has no orders and shows up with zero. A plain Join is an inner join and would drop Dua. When people write a join and wonder where some rows went, this is usually why.

SelectMany flattens. Each string produces an array of parts, and SelectMany merges all the arrays into one sequence. With Select you would get an array of arrays.

Deferred execution

This is the part that trips up experienced developers. A query like numbers.Where(n => n > 1) does not run when you write it. It describes work and runs when you enumerate it, with foreach, ToList, Count and so on. So when I added 4 to the list before enumerating, the query saw it. Calling ToList() runs the query at once and freezes the result.

The consequence: if you enumerate the same query three times, it runs three times. For an in-memory list that costs a little. For a database query it means three round trips. If you need the results more than once, call ToList() and keep it.

First, Single and the OrDefault versions

MethodNo matchMore than one match
Firstthrowsreturns the first
FirstOrDefaultreturns default (null for classes)returns the first
Singlethrowsthrows
SingleOrDefaultreturns defaultthrows

Use Single when exactly one result is a rule of your data, such as lookup by a unique id. It then acts as a check. Use FirstOrDefault when "none" is an acceptable answer.

Common mistakes

  • Enumerating a query many times and paying for it each time.
  • Modifying a collection while a deferred query over it is running.
  • Using Count() > 0 instead of Any(). Any can stop at the first item.
  • Sorting with OrderBy twice to sort by two keys. The second call discards the first. Use ThenBy.
  • Writing LINQ that is too clever. If a chain needs a comment on every line, a loop may read better.

Try it yourself

  1. Print the city with the highest total spending across its customers.
  2. List the customers who have placed no orders.
  3. Show each customer's most expensive order. Hint: MaxBy inside a group or a select.
  4. Turn the paging example into a method GetPage(int page, int size).
csharp
var customers = new List<Customer>
{
    new(1, "Ayesha", "Lahore"),
    new(2, "Bilal", "Karachi"),
    new(3, "Chand", "Lahore"),
    new(4, "Dua", "Islamabad")
};

var orders = new List<Order>
{
    new(100, 1, 2500m, "Books"),
    new(101, 1, 900m, "Stationery"),
    new(102, 2, 15000m, "Electronics"),
    new(103, 3, 400m, "Books"),
    new(104, 3, 7200m, "Electronics"),
    new(105, 1, 3100m, "Electronics")
};

// Filter, sort, project
var big = orders
    .Where(o => o.Total >= 2000m)
    .OrderByDescending(o => o.Total)
    .Select(o => $"#{o.Id}: {o.Total:N0}");
Console.WriteLine(string.Join(" | ", big));

// Group and aggregate
var byCategory = orders
    .GroupBy(o => o.Category)
    .Select(g => new { Category = g.Key, Count = g.Count(), Sum = g.Sum(o => o.Total) })
    .OrderByDescending(x => x.Sum);
foreach (var row in byCategory)
{
    Console.WriteLine($"{row.Category,-12} {row.Count} orders, {row.Sum:N0}");
}

// Join: customer name with their spending
var spending = customers
    .GroupJoin(orders, c => c.Id, o => o.CustomerId,
        (c, os) => new { c.Name, c.City, Spent = os.Sum(o => o.Total) })
    .OrderByDescending(x => x.Spent);
foreach (var s in spending)
{
    Console.WriteLine($"{s.Name,-8} {s.City,-10} {s.Spent,8:N0}");
}

// SelectMany flattens
var tags = new[] { "a,b", "b,c", "d" }
    .SelectMany(t => t.Split(','))
    .Distinct();
Console.WriteLine(string.Join("", tags));

// Single value queries
Console.WriteLine(orders.Any(o => o.Total > 10000m));
Console.WriteLine(orders.All(o => o.Total > 100m));
Console.WriteLine(orders.Max(o => o.Total));
Console.WriteLine(orders.MaxBy(o => o.Total)!.Id);
Console.WriteLine(customers.FirstOrDefault(c => c.City == "Multan")?.Name ?? "nobody");

// Deferred execution
var numbers = new List<int> { 1, 2, 3 };
var query = numbers.Where(n => n > 1);     // nothing runs yet
numbers.Add(4);
Console.WriteLine(string.Join(",", query)); // 2,3,4 - runs now
var snapshot = numbers.Where(n => n > 1).ToList();  // runs now, result frozen
numbers.Add(5);
Console.WriteLine(snapshot.Count);          // 3

// Paging
var page2 = orders.OrderBy(o => o.Id).Skip(2).Take(2);
Console.WriteLine(string.Join(",", page2.Select(o => o.Id)));

record Customer(int Id, string Name, string City);
record Order(int Id, int CustomerId, decimal Total, string Category);

This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.

Sign up free I already have an account