Search code examples
c#sortingicomparable

Reverse Sorting with IComparable


I have code like this -

List<User> users;
protected class User : IComparable<User>
{
    public string name;
    public string email;
    public decimal total;
    public string address;
    public string company;
    public string origin;
    public int CompareTo(User b)
    {
        return this.total.CompareTo(b.total);

    }
}

For a table that is sorted by the number of points a user has. It sorts in ascending order, but need to change it to descending order. It uses users.Sort(), but I can't seem to figure out how to make it sort in reverse order.


Solution

  • If you want to reverse the order, just reverse the comparison:

    public int CompareTo(User b)
    {
        return b.total.CompareTo(this.total);
    }