IComparable

class Person : IComparable<Person>
{
    public int Age { get; set; }
    public string Name { get; set; }

    public int CompareTo(Person other)
    {
          // Alphabetic sort if age is equal. [A to Z]
          if (this.Age== other.Age) {
                return this.Name.CompareTo(other.Name);
          }
          // Default to age sort. [High to low]
         return this.Age.CompareTo(other.Age);
    }

    public override string ToString()
    {
        // String representation.
        return this.Age.ToString() + “,” + this.Name;
    }
}

class Program
{
    static void Main()
    {
List<Person> list = new List<Person>();
list.Add(new Person() { Name = “Steve”, Age = 10 });
list.Add(new Person() { Name = “Janet”, Age = 11 });
list.Add(new Person() { Name = “Andrew”, Age = 10 });
list.Add(new Person() { Name = “Bill”, Age = 5 });
list.Add(new Person() { Name = “Lucy”, Age = 8 });

// Uses IComparable.CompareTo()
list.Sort();

// Uses Person.ToString
foreach (var element in list)
{
    Console.WriteLine(element);
}
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *