LINQ in depth: deferred execution, grouping and joins
Course contents (16 lessons)
- The type system
- Records, structs and value equality
- Interfaces and abstract classes
- Generics and constraints
- Delegates, events and lambdas
- Querying and matching data
- LINQ in depth: deferred execution, grouping and joins
- IEnumerable versus IQueryable
- Pattern matching in modern C#
- Async and await: how Task really works
- Async patterns: cancellation, timeouts and async streams
- Application structure
- Dependency injection and service lifetimes
- Configuration, options and logging
- Data and web
- Entity Framework Core basics: DbContext, migrations and queries
- Building a minimal API with ASP.NET Core
- Unit testing with xunit
- Performance and the final project
- Performance basics: Span of T and fewer allocations
- 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
| Method | No match | More than one match |
|---|---|---|
First | throws | returns the first |
FirstOrDefault | returns default (null for classes) | returns the first |
Single | throws | throws |
SingleOrDefault | returns default | throws |
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() > 0instead ofAny(). Any can stop at the first item. - Sorting with
OrderBytwice to sort by two keys. The second call discards the first. UseThenBy. - Writing LINQ that is too clever. If a chain needs a comment on every line, a loop may read better.
Try it yourself
- Print the city with the highest total spending across its customers.
- List the customers who have placed no orders.
- Show each customer's most expensive order. Hint:
MaxByinside a group or a select. - Turn the paging example into a method
GetPage(int page, int size).
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