LINQ: querying collections with Where, Select and GroupBy
In week 4 you went through collections with loops: one for to add up, another to find the largest, another to filter. It works, but it takes effort to write and read. LINQ (Language Integrated Query) is a set of methods that comes with .NET and lets you express those operations in one line, with names that say what they do: filter, transform, sort, group, count. It works with arrays, lists, dictionaries and anything you can go through with foreach. In new projects it is already available without writing any using.
Filtering, transforming and sorting
The three basic methods are Where (keeps the elements that meet a condition), Select (transforms each element into something else) and OrderBy (sorts; OrderByDescending the other way, ThenBy for a second criterion). Conditions are written with lambda expressions: x => x > 5 reads "given x, return x greater than 5". Methods are chained, so the result of one goes into the next. To get a concrete list or array at the end you use ToList or ToArray; until you do, the query is only a description that runs when someone goes through it, which is called deferred execution.
int[] numbers = [8, 3, 12, 5, 20, 7, 14];
var bigEven = numbers.Where(n => n > 5 && n % 2 == 0).ToList();
Console.WriteLine(string.Join(", ", bigEven)); // 8, 12, 20, 14
var squares = numbers.Select(n => n * n).OrderBy(n => n).Take(3);
Console.WriteLine(string.Join(", ", squares)); // 9, 25, 49
string[] names = ["Marta", "Ana", "Luis", "Bea", "Carlos"];
var sorted = names.OrderBy(n => n.Length).ThenBy(n => n);
Console.WriteLine(string.Join(", ", sorted)); // Ana, Bea, Luis, Marta, Carlos
var upper = names.Where(n => n.StartsWith('M') || n.StartsWith('C'))
.Select(n => n.ToUpper());
Console.WriteLine(string.Join(", ", upper)); // MARTA, CARLOSAsking questions and summarizing
Another family of methods returns a single value: Count, Sum, Average, Min and Max summarize the collection; Any asks whether at least one element exists (with or without a condition) and All whether every element meets the condition; First and Single return one element and throw an exception if they do not find it, while FirstOrDefault returns null (or the default value) when there is none. With nullability enabled, that null forces you to check the result, which is an advantage. Avoid Count() > 0 if you only want to know whether anything exists: Any() is clearer and, on large collections, more efficient.
var orders = new List<Order>
{
new("Ana", "Books", 30m),
new("Luis", "Games", 60m),
new("Ana", "Games", 45m),
new("Marta", "Books", 15m),
new("Luis", "Books", 25m),
};
Console.WriteLine(orders.Sum(o => o.Total)); // 175
Console.WriteLine(orders.Average(o => o.Total)); // 35
Console.WriteLine(orders.Max(o => o.Total)); // 60
Console.WriteLine(orders.Any(o => o.Total > 50)); // True
Console.WriteLine(orders.All(o => o.Total > 20)); // False
Order? first = orders.FirstOrDefault(o => o.Customer == "Marta");
Console.WriteLine(first?.Total); // 15
Console.WriteLine(orders.FirstOrDefault(o => o.Customer == "Nobody") is null); // True
record Order(string Customer, string Category, decimal Total);Grouping with GroupBy
GroupBy gathers elements according to a key and returns groups; each group has its Key and can be traversed or summarized like any other collection. It is the ideal tool for reports: spending by category, sales by customer, words by initial. It is combined with Select to turn each group into a result. ToDictionary builds a dictionary from a collection, useful for fast lookup by key. When a query becomes too long, split it into intermediate variables with clear names: LINQ is powerful, but the code must remain readable.
// uses the same orders list and Order record as the previous example
var byCategory = orders
.GroupBy(o => o.Category)
.Select(g => new { Category = g.Key, Count = g.Count(), Total = g.Sum(o => o.Total) })
.OrderByDescending(x => x.Total);
foreach (var row in byCategory)
{
Console.WriteLine($"{row.Category}: {row.Count} orders, total {row.Total}");
}
// Games: 2 orders, total 105
// Books: 3 orders, total 70
Dictionary<string, decimal> perCustomer = orders
.GroupBy(o => o.Customer)
.ToDictionary(g => g.Key, g => g.Sum(o => o.Total));
Console.WriteLine(perCustomer["Ana"]); // 75
record Order(string Customer, string Category, decimal Total);Test what you learned
Question 1 of 2What does Where do in LINQ?
✎ My notes
Saved only in this browser. Sign in to keep it in your account.0/5000 characters