IComparable
In this page:
IComparable
IComparable<T> defines a single method, CompareTo, that lets objects define their own natural ordering. Implementing it allows a type to be sorted with Array.Sort or List<T>.Sort without any extra comparer. CompareTo returns negative, zero, or positive to indicate less-than, equal, or greater-than.
Note: Implement IComparable<T> whenever a type has an obvious natural sort order, like a numeric score.
Example: IComparable
using System;
using System.Collections.Generic;
class Player : IComparable<Player>
{
public string Name;
public int Score;
public Player(string name, int score)
{
Name = name;
Score = score;
}
public int CompareTo(Player other)
{
return Score.CompareTo(other.Score);
}
}
class Program
{
static void Main(string[] args)
{
List<Player> players = new List<Player>
{
new Player("Ana", 50),
new Player("Ben", 90),
new Player("Cid", 20),
};
players.Sort();
foreach (Player p in players)
{
Console.WriteLine($"{p.Name}: {p.Score}");
}
}
}
Login to try C/C++/Java/PHP code in the editor
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: