Lesson 4: Sorting & Grouping with LINQ
Sorting and grouping are essential when preparing data for reports, dashboards, or UI displays. LINQ makes both easy with semantic operators.
OrderBy and OrderByDescending
Use OrderBy to sort ascending and OrderByDescending to sort descending.
var products = new[]
{
new { Name = "Notebook", Price = 4.99m },
new { Name = "Mouse", Price = 19.99m },
new { Name = "Headset", Price = 49.99m }
};
var sorted = products.OrderBy(p => p.Price);
var highToLow = products.OrderByDescending(p => p.Price);
ThenBy for Multi-Level Sorting
ThenBy and ThenByDescending sort by additional keys after the primary sort.
var people = new[]
{
new { Name = "Mia", City = "Boston" },
new { Name = "Ava", City = "Austin" },
new { Name = "Leo", City = "Boston" }
};
var ordered = people
.OrderBy(p => p.City)
.ThenBy(p => p.Name);
GroupBy Basics
GroupBy collects items by a key. Each group is represented as an IGrouping<TKey, TElement>.
var sales = new[]
{
new { Region = "West", Amount = 1200 },
new { Region = "East", Amount = 900 },
new { Region = "West", Amount = 700 }
};
var grouped = sales.GroupBy(s => s.Region);
foreach (var group in grouped)
{
Console.WriteLine(group.Key);
foreach (var sale in group)
{
Console.WriteLine($" - {sale.Amount}");
}
}
Group Aggregation
GroupBy is often followed by aggregation to summarize each group.
var totals = sales
.GroupBy(s => s.Region)
.Select(g => new { Region = g.Key, Total = g.Sum(s => s.Amount) });
🧠 Quick Check — Lesson 4
Which operator sorts items by a secondary key after the primary sort?
Ordering with Multiple Fields
Multiple sort criteria are useful when primary values match and you want a deterministic order.
var items = new[]
{
new { Category = "Book", Title = "C# Guide" },
new { Category = "Book", Title = "LINQ Recipes" },
new { Category = "Game", Title = "Code Quest" }
};
var sortedItems = items
.OrderBy(item => item.Category)
.ThenBy(item => item.Title);
Lesson Summary
OrderBy sorts ascending while OrderByDescending sorts descending.
ThenBy adds a secondary sort when the primary values match.
GroupBy creates groups keyed by a selected value and supports aggregation.
Group results can be transformed with Select to produce summaries like totals.