Two ideas make the difference between using LINQ and understanding it: GroupBy for building summaries, and deferred execution, which explains the surprising bugs.
GroupBy
GroupBy sorts items into buckets by a key. Each group has a Key and can be looped over or queried like any sequence. Groups appear in order of each key's first appearance.
var sales = new[]
{
new Sale("tea", 3),
new Sale("cake", 5),
new Sale("tea", 2),
};
var totals = sales.GroupBy(sale => sale.Item)
.Select(group => $"{group.Key}: {group.Count()} sales, {group.Sum(sale => sale.Amount)} total");
foreach (string line in totals)
{
Console.WriteLine(line);
}
record Sale(string Item, int Amount);Check your prediction
tea: 2 sales, 5 total
cake: 1 sales, 5 totalBuilding collections
ToList and ToArray copy results into a collection. ToDictionary builds one from a key and a value, and throws if a key repeats. ToHashSet does what its name says. Distinct, Concat and Zip round out the common toolkit.
string[] words = { "one", "three", "two", "one" };
Dictionary<string, int> lengths = words.Distinct().ToDictionary(word => word, word => word.Length);
Console.WriteLine(lengths["three"]);
var byLength = words.GroupBy(word => word.Length).ToDictionary(group => group.Key, group => group.Count());
Console.WriteLine(byLength[3]);
var numbered = words.Zip(Enumerable.Range(1, 4), (word, number) => $"{number}:{word}");
Console.WriteLine(string.Join(" ", numbered));Check your prediction
5
3
1:one 2:three 3:two 4:oneA query isn't its results
Here's the key fact: Where and Select do no work when you call them. They build a description, like the iterators you wrote on Day 2. The work happens when something loops over it. If the source has changed by then, the results change too.
var numbers = new List<int> { 1, 2, 3 };
var large = numbers.Where(n => n > 1);
numbers.Add(10);
Console.WriteLine(large.Count());
numbers.Clear();
Console.WriteLine(large.Count());Check your prediction
3
0Each loop over large is a fresh run. If the query is expensive or has effects, it repeats each time. ToList runs it now, once, and takes a snapshot.
int calls = 0;
var numbers = new[] { 1, 2 };
var lazy = numbers.Select(n =>
{
calls++;
return n * 2;
});
lazy.Count();
lazy.Sum();
Console.WriteLine(calls);
calls = 0;
List<int> saved = lazy.ToList();
saved.Count();
saved.Sum();
Console.WriteLine(calls);Check your prediction
4
2The rule of thumb: if you'll use a query's results more than once, or the source may change, end it with ToList. Conversely, don't add ToList in the middle of a chain without a reason, because laziness lets Any and First stop early. Keep lambdas in queries free of side effects as well. calls++ is here only to show what's happening.
Fix it: Two orders for one customer
This turns a list of orders into a dictionary of totals by customer. Run it.
var orders = new[] { ("Ana", 10), ("Ben", 5), ("Ana", 20) };
Dictionary<string, int> totals = orders.ToDictionary(order => order.Item1, order => order.Item2);
foreach (var (name, total) in totals)
{
Console.WriteLine($"{name}: {total}");
}Check your prediction
ArgumentException
An item with the same key has already been addedToDictionary makes one entry per item, and Ana has two orders, so the second Ana collides with the first. Fix it so each customer appears once with their total.
Fix it
Group first, so there's one item per customer, and then build the dictionary from the groups:
var orders = new[] { ("Ana", 10), ("Ben", 5), ("Ana", 20) };
Dictionary<string, int> totals = orders
.GroupBy(order => order.Item1)
.ToDictionary(group => group.Key, group => group.Sum(order => order.Item2));
foreach (var (name, total) in totals)
{
Console.WriteLine($"{name}: {total}");
}Ana: 30
Ben: 5Use ToDictionary straight away only when the key is unique, such as an id. Its exception is useful then: a duplicate id is a data error you want to hear about.
Your turn
Summarize orders
With the Order record in the workspace, build a list summary, using one query, with one record CustomerTotal(string Customer, int Orders, decimal Total) per customer. Only count orders that aren't cancelled. Sort by total, highest first. Print each result as Ana: 2 orders, 30.
Then show that your query really ran once. After creating summary, add a new order for Zed, and print the summary's count.
When it works, it prints:
Ana: 2 orders, 30
Cy: 1 orders, 7
Ben: 1 orders, 5
3var orders = new List<Order>
{
new("Ana", 10m, false),
new("Ben", 5m, false),
new("Ana", 20m, false),
new("Ben", 100m, true),
new("Cy", 7m, false),
};
Console.WriteLine(orders.Count);
record Order(string Customer, decimal Amount, bool Cancelled);Hint 1: the idea
Filter, group by customer, turn each group into a CustomerTotal, sort, and finish with ToList. The order of those steps matters.
Hint 2: a first step
Write the Where and GroupBy, then use Select to print each group's Key and Count() before you introduce the new record.
Show one solution
var orders = new List<Order>
{
new("Ana", 10m, false),
new("Ben", 5m, false),
new("Ana", 20m, false),
new("Ben", 100m, true),
new("Cy", 7m, false),
};
List<CustomerTotal> summary = orders
.Where(order => !order.Cancelled)
.GroupBy(order => order.Customer)
.Select(group => new CustomerTotal(group.Key, group.Count(), group.Sum(order => order.Amount)))
.OrderByDescending(total => total.Total)
.ToList();
orders.Add(new Order("Zed", 1m, false));
foreach (CustomerTotal total in summary)
{
Console.WriteLine($"{total.Customer}: {total.Orders} orders, {total.Total}");
}
Console.WriteLine(summary.Count);
record Order(string Customer, decimal Amount, bool Cancelled);
record CustomerTotal(string Customer, int Orders, decimal Total);Ana: 2 orders, 30
Cy: 1 orders, 7
Ben: 1 orders, 5
3Cancelled orders are removed before grouping, so Ben's cancelled 100 never reaches his total. ToList() at the end runs the query once and keeps the results. That's why adding Zed afterwards doesn't change the count: without it, summary would be a query, and printing it would run it again and include Zed. Each group becomes a small CustomerTotal record, so the printing loop reads named values instead of recomputing them.
Completion is saved in this browser only. It does not measure mastery.