c# · level 2 · unit 5 · lesson 3
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
sorts by whatever you pick.
OrderBy sorts by whatever the lambda picks, with no IComparable needed. kids.OrderBy(k => k.Age) lines the children up from youngest to oldest. Text sorts from A to Z, and numbers smallest first.
sorts the other way, biggest first. When two items tie, like Mia and Ava who are both 9, add to sort the tied ones by a second choice. Without it, tied items keep their original order.
Like Where, they hand back a new sequence and leave the list alone.
using System;
using System.Collections.Generic;
using System.Linq;
var kids = new List<Kid>
{
new Kid("Mia", 9),
new Kid("Leo", 7),
new Kid("Ava", 9),
new Kid("Sam", 8)
};
var youngest = kids.OrderBy(k => k.Age).ThenBy(k => k.Name);
Console.WriteLine(string.Join(", ", youngest.Select(k => $"{k.Name} {k.Age}")));
var oldest = kids.OrderByDescending(k => k.Age).Select(k => k.Name);
Console.WriteLine(string.Join(", ", oldest));
record Kid(string Name, int Age); A long collection initialiser can spread over several lines, one item per line.
guess first
Short words first, then A to Z. 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 words = new List<string> { "pear", "fig", "banana", "kiwi" };
var sorted = words.OrderBy(w => w.Length).ThenBy(w => w);
Console.WriteLine(string.Join(" ", sorted));
your turn
Your turn. Build the leaderboard.
Add yourself on line 9 with any score. On line 11, sort by points so the biggest score comes first. Press run.
output
press run to see what happens
fix it
The least popular cake came first. Fix it!
output
press run to see what happens
- Lemon, with only 4 votes, comes first. Which way does
OrderByon line 11 sort? OrderByputs the smallest first. You want the biggest number of votes first.- Change
OrderBytoOrderByDescendingon line 11, then press run.
nailed it
you can sort by anything. :D
OrderBysorts smallest first by what the lambda picks.OrderByDescendingputs the biggest first.ThenBybreaks ties with a second choice.
new words in your collection
- OrderBy
- OrderByDescending
- ThenBy
This lesson isn’t saved. A free account remembers every lesson you finish.