×

c# · level 3 · unit 3 · lesson 2

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. 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.