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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With