12

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.

d219
  • 2,707
  • 5
  • 31
  • 36

4 Answers4

16

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

public int CompareTo(User b)
{
    return b.total.CompareTo(this.total);
}
Selman Genç
  • 100,147
  • 13
  • 119
  • 184
6

If your User class can be changed to sort in reverse order, you can try other answers which suggests modifying CompareTo method. Otherwise try the following.

users.Sort();//Sort normally
users.Sort((x, y) => y.CompareTo(x));//Reverse sort
Sriram Sakthivel
  • 72,067
  • 7
  • 111
  • 189
3

Just reverse the parameters in your comparison. So instead of:

return this.total.CompareTo(b.total);

Just do:

return b.total.CompareTo(this.total);
DavidG
  • 113,891
  • 12
  • 217
  • 223
1
public int CompareTo(User b)
{
    return this.total.CompareTo(b.total) * -1;

}
TimChang
  • 2,249
  • 13
  • 25
  • 1
    Edge case problem here! CompareTo doesn't limit range of return values, and due to 2s complement numbers and overflow we have the situation where (Int32.MinValue * -1 == int32.MinValue) which could cause a problem. – Paul Westcott Oct 25 '19 at 21:36