c# · level 3 · unit 3 · lesson 4
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
Two folds. 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 digits = new List<int> { 3, 1, 4 };
string trail = digits.Aggregate("start", (text, d) => text + "-" + d);
int product = digits.Aggregate(1, (total, d) => total * d);
Console.WriteLine(trail);
Console.WriteLine(product);
your turn
Your turn. Count the words.
On line 6, give SelectMany a lambda that turns each line into its words with Split(' ').
output
press run to see what happens
fix it
The empty basket crashes the till. Can you fix it?
output
press run to see what happens
- It crashes with
InvalidOperationExceptionon line 6. What is in the basket? - With no seed,
Aggregatestarts from the first item, and an empty basket has none. - Give
Aggregatea seed of0before the lambda on line 6, then run.
nailed it
you can flatten and fold any sequence. :D
SelectManyturns lists of lists into one sequence.Aggregatefolds a sequence into one value.- A seed keeps
Aggregatesafe on empty sequences.
new words in your collection
- flatten
- seed
- accumulator
This lesson isn’t saved. A free account remembers every lesson you finish.