Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

comparing two objects by two properties

How to sort two objects in a list by using two properties one by ascending and the other by descending order. when linq is used it says i need to implement IComparer interface but not sure how to compare two objects by using two properties at once.

Say Person class by Name ascending and Age descending.

like image 728
TrustyCoder Avatar asked Apr 12 '26 22:04

TrustyCoder


1 Answers

Well, you need to decide which is your primary comparison. Only use the secondary comparison if the first one gives equality. For example:

public int Compare(Person p1, Person p2)
{
    int primary = p1.Name.CompareTo(p2.Name);
    if (primary != 0)
    {
        return primary;
    }
    // Note reverse order of comparison to get descending
    return p2.Age.CompareTo(p1.Age);
}

(This can be written more compactly in various ways, but I've kept it very explicit so you can understand the concepts.)

Note that in MiscUtil I have some building blocks so you can easily construct comparers using lambda expressions, compose comparers etc.

like image 107
Jon Skeet Avatar answered Apr 14 '26 10:04

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!