C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Also: The Employee class provides the CompareTo(Employee) method and the ToString method.
CompareTo: The method returns int—this indicates which Employee should be ordered first. We want to sort by the Salary from highest to lowest.
However: If Salary is equal, we want to sort alphabetically. We check for equal Salary values, and in that case sort alphabetically.
Main: Here we create a List of Employee instances. These are sorted first by Salary and then by Name.
ListC# program that implements IComparable interface
using System;
using System.Collections.Generic;
class Employee : IComparable<Employee>
{
public int Salary { get; set; }
public string Name { get; set; }
public int CompareTo(Employee other)
{
// Alphabetic sort if salary is equal. [A to Z]
if (this.Salary == other.Salary)
{
return this.Name.CompareTo(other.Name);
}
// Default to salary sort. [High to low]
return other.Salary.CompareTo(this.Salary);
}
public override string ToString()
{
// String representation.
return this.Salary.ToString() + "," + this.Name;
}
}
class Program
{
static void Main()
{
List<Employee> list = new List<Employee>();
list.Add(new Employee() { Name = "Steve", Salary = 10000 });
list.Add(new Employee() { Name = "Janet", Salary = 10000 });
list.Add(new Employee() { Name = "Andrew", Salary = 10000 });
list.Add(new Employee() { Name = "Bill", Salary = 500000 });
list.Add(new Employee() { Name = "Lucy", Salary = 8000 });
// Uses IComparable.CompareTo()
list.Sort();
// Uses Employee.ToString
foreach (var element in list)
{
Console.WriteLine(element);
}
}
}
Output
500000,Bill
10000,Andrew
10000,Janet
10000,Steve
8000,Lucy
Fragment that sorts on Salary: high to low
return other.Salary.CompareTo(this.Salary);
Sorts on Salary: low to high
return this.Salary.CompareTo(other.Salary);
Caution: This approach may be less robust and exhibit poorer object-orientation. But in many cases, it is acceptable.
Sort TupleSort List