LINQ Advanced: GroupBy, Join, Aggregate and More
Sample Data
csharp
record Customer(int Id, string Name, string City);
record Order(int Id, int CustomerId, decimal Total);
var customers = new List<Customer>
{
new(1, "Ana", "Paris"),
new(2, "Raj", "Delhi"),
new(3, "Mei", "Paris")
};
var orders = new List<Order>
{
new(100, 1, 50m), new(101, 1, 70m), new(102, 2, 30m), new(103, 3, 90m)
};
GroupBy
csharp
var byCity = customers.GroupBy(c => c.City);
foreach (var group in byCity)
{
Console.WriteLine($"{group.Key}: {group.Count()} customers");
foreach (var c in group)
Console.WriteLine($" {c.Name}");
}
csharp
var totals = orders
.GroupBy(o => o.CustomerId)
.Select(g => new { CustomerId = g.Key, Orders = g.Count(), Sum = g.Sum(o => o.Total) });
Join
csharp
var report = customers.Join(
orders,
c => c.Id, // key from customers
o => o.CustomerId, // key from orders
(c, o) => new { c.Name, o.Id, o.Total });
foreach (var row in report)
Console.WriteLine($"{row.Name}: order {row.Id} = {row.Total:C}");
Join is an inner join: Customers without orders are left out. For a left join, use
GroupJoin (or LeftJoin, added in newer .NET versions).
SelectMany: Flatten
csharp
var sentences = new[] { "learn dotnet", "build apps" };
var words = sentences.SelectMany(s => s.Split(' '));
Console.WriteLine(string.Join(", ", words)); // learn, dotnet, build, apps
Distinct, Zip, Concat
csharp
var cities = customers.Select(c => c.City).Distinct(); // Paris, Delhi
var letters = new[] { "A", "B", "C" };
var numbers = new[] { 1, 2, 3 };
var pairs = letters.Zip(numbers, (l, n) => $"{l}{n}"); // A1, B2, C3
ToDictionary and ToLookup
csharp
var byId = customers.ToDictionary(c => c.Id);
Console.WriteLine(byId[2].Name); // Raj
Aggregate: Build Your Own Total
csharp
int[] numbers2 = { 1, 2, 3, 4 };
int product = numbers2.Aggregate(1, (acc, n) => acc * n); // 24
Newer Helpers (.NET 9 and later)
csharp
var cityCounts = customers.CountBy(c => c.City); // Paris: 2, Delhi: 1
foreach (var (city, count) in cityCounts)
Console.WriteLine($"{city}: {count}");
| Operator | Use for |
|---|---|
GroupBy | Group items by a key |
Join | Combine two lists by matching keys |
SelectMany | Flatten lists of lists |
Distinct | Remove duplicates |
ToDictionary | Make a fast lookup |
Aggregate | Custom running calculation |
CountBy, AggregateBy | Short forms of group and count |
Performance: For big in-memory data, build a
Dictionary or HashSet once instead of searching a list inside a loop.
Conclusion
GroupBy, Join and SelectMany handle most reporting tasks. When using Entity Framework later, the same LINQ becomes SQL.
Quick Summary: GroupBy groups, Join combines, SelectMany flattens, ToDictionary builds lookups.

