c# · level 2 · unit 3 · lesson 4
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
tells Sort which object comes first.
.Sort() knows how to order numbers and text, but not your own objects. Is a kite bigger than a robot? You decide, by implementing the built-in interface IComparable<Toy>, which promises one method: .
a.CompareTo(b) gives a negative number when a comes first, zero when they tie, and a positive number when b comes first. Numbers and strings have their own CompareTo, so Price.CompareTo(other.Price) orders toys from cheapest to dearest.
Call .Sort() on a list of objects with no IComparable, and it stops with InvalidOperationException.
using System;
using System.Collections.Generic;
var toys = new List<Toy> { new Toy("kite", 8), new Toy("yo-yo", 2), new Toy("robot", 25) };
toys.Sort();
Console.WriteLine($"{toys[0].Name}, {toys[1].Name}, {toys[2].Name}");
class Toy : IComparable<Toy>
{
public string Name { get; set; }
public int Price { get; set; }
public Toy(string name, int price)
{
Name = name;
Price = price;
}
public int CompareTo(Toy other) { return Price.CompareTo(other.Price); }
} Swap the two sides, other.Price.CompareTo(Price), and the order flips.
guess first
Who is first after sorting? 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;
var runners = new List<Runner> { new Runner("Ava", 31), new Runner("Ben", 28), new Runner("Cy", 35) };
runners.Sort();
Console.WriteLine(runners[0].Name);
class Runner : IComparable<Runner>
{
public string Name { get; set; }
public int Minutes { get; set; }
public Runner(string name, int minutes)
{
Name = name;
Minutes = minutes;
}
public int CompareTo(Runner other) { return other.Minutes.CompareTo(Minutes); }
}
your turn
Your turn. Line up the books.
On line 8, make Book comparable with other books. On line 17, compare pages so the shortest book comes first. Press run.
output
press run to see what happens
fix it
The leaderboard will not sort. Fix it!
output
press run to see what happens
- C# stops with
InvalidOperationExceptionon line 5.Playerhas aCompareTo, but doesSortknow that? Sortonly usesCompareTowhen the class promises it by implementing an interface.- Change line 8 to
class Player : IComparable<Player>, then press run.
nailed it
your objects know their order. :D
- Implement
IComparable<T>to make objects sortable. CompareTogives negative, zero or positive.- Swap the two sides to flip the order.
new words in your collection
- IComparable
- CompareTo
This lesson isn’t saved. A free account remembers every lesson you finish.