views:

70

answers:

3

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.

A: 

Try this "Implementing IComparer for Sorting Custom Objects"

Xander
+7  A: 

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.

Jon Skeet
+4  A: 

If you want to create a new copy of the list (so you still have the original order in your original list), you can do this:

List<Person> unsortedList;

sortedList = unsortedList.OrderBy(p => p.Name).ThenByDescending(p => p.Age);
teedyay