c# · level 3 · unit 3 · lesson 2
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
GroupBy sorts items into labelled piles.
GroupBy walks your data and drops each item onto a pile, chosen by a : the lambda that picks what to group by. sales.GroupBy(s => s.Shop) makes one pile per shop. Each pile is a : its Key is the shop, and the grouping itself is a sequence of that shop's sales.
Because a grouping is a sequence, all of LINQ works on it: shop.Count(), shop.Sum(s => s.Amount), shop.Max(...). Groups come out in the order their keys first appear, so add OrderBy when a report must be sorted.
using System;
using System.Collections.Generic;
using System.Linq;
var sales = new List<Sale>
{
new Sale("Leeds", 30), new Sale("York", 12), new Sale("Leeds", 45),
new Sale("Bath", 20), new Sale("York", 8),
};
foreach (var shop in sales.GroupBy(s => s.Shop).OrderBy(g => g.Key))
{
Console.WriteLine($"{shop.Key}: {shop.Sum(s => s.Amount)} from {shop.Count()}");
}
record Sale(string Shop, int Amount); The var in the loop is an IGrouping<string, Sale>: a key and its items.
guess first
No sorting this time. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
using System;
using System.Collections.Generic;
using System.Linq;
var votes = new List<string> { "tea", "coffee", "tea", "juice", "coffee", "tea" };
foreach (var drink in votes.GroupBy(v => v))
{
Console.WriteLine($"{drink.Key} {drink.Count()}");
}
your turn
Your turn. Total the club points.
Fill in the key selector on line 10 so the runners are grouped by club. Then, on line 12, choose what to add up for each club.
output
press run to see what happens
fix it
The chip shop report shows strange names. Can you fix it?
output
press run to see what happens
- The counts are right, but the names look like
System.Linq.Grouping. What does line 8 print first? dishis the whole grouping. The value it was grouped by lives in one property.- Change
{dish}to{dish.Key}on line 8, then run.
nailed it
you can summarise any data by group. :D
- A key selector decides which pile each item joins.
- A grouping has a
Keyand is a sequence itself. - Groups keep first-appearance order, so sort reports.
new words in your collection
- key selector
- grouping
This lesson isn’t saved. A free account remembers every lesson you finish.