×

c# · level 3 · unit 3 · lesson 4

  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

SelectMany flattens, Aggregate folds.

Select gives one result per item. When each item holds several things, like an order holding several products, Select hands back a list of lists. SelectMany flattens them: every inner item lands in one long sequence, ready for Distinct, Count or GroupBy.

Aggregate goes the other way and folds a whole sequence into one value. You give a starting value, the , and a lambda that takes the so far plus the next item, then returns the new accumulator. Sum is one fold someone wrote for you. Aggregate lets you write any fold.

using System;
using System.Collections.Generic;
using System.Linq;

var orders = new List<string[]>
{
    new[] { "tea", "milk" },
    new[] { "bread" },
    new[] { "milk", "eggs", "tea" },
};
var everything = orders.SelectMany(items => items).ToList();
Console.WriteLine(everything.Count);
Console.WriteLine(string.Join(", ", everything.Distinct()));
int longest = everything.Aggregate(0, (best, item) => Math.Max(best, item.Length));
Console.WriteLine(longest);

new[] { "tea", "milk" } makes an array and lets C# work out its type.