×

c# · level 2 · unit 5 · lesson 3

  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

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.