user3896016
user3896016

Reputation:

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.

Upvotes: 12

Views: 12427

Answers (4)

TimChang
TimChang

Reputation: 2417

public int CompareTo(User b)
{
    return this.total.CompareTo(b.total) * -1;

}

Upvotes: 1

Sriram Sakthivel
Sriram Sakthivel

Reputation: 73442

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

Upvotes: 7

DavidG
DavidG

Reputation: 118937

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

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

Just do:

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

Upvotes: 3

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101680

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

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

Upvotes: 16

Related Questions