anon
anon

Reputation:

How to sort a list with two sorting rules?

I have a list that I want to sort using to parameters. That means it are all values and if for example I have

A    2/2
B    3/3
C    3/4

I want the sorting C B A

I tried to implement that the following way:

methods.Sort((y, x) => x.GetChangingMethodsCount().CompareTo(y.GetChangingMethodsCount()));
            methods.Sort((y, x) => x.GetChangingClassesCount().CompareTo(y.GetChangingClassesCount()));

First sort the list with the second parameter and then sort it again with the first parameter. But the ordering isn0t correct. Any hints how to achieve that?

Upvotes: 0

Views: 496

Answers (3)

Gabe
Gabe

Reputation: 86768

What you need to do is combine the two sort keys into a single function. If the first comparison returns 0, only then try the second one:

methods.Sort((y, x) => 
{
    int sort = x.GetChangingClassesCount().CompareTo(y.GetChangingClassesCount());
    if (sort == 0)
        sort = x.GetChangingMethodsCount().CompareTo(y.GetChangingMethodsCount());
    return sort;
});

Upvotes: 4

Tomas Vana
Tomas Vana

Reputation: 18775

Probably the easiest way is to use the OrderBy and ThenBy extension methods like that :

methods.OrderByDescending(x => x.GetChangingMethodCount()).
        ThenByDescending(x => x.GetChangingClassesCount()).
        ToList();

Upvotes: 3

Kristof Claes
Kristof Claes

Reputation: 10941

It's not clear (to me at least) if this is what you want based on your example, but you could give this a try:

var sortedMethods = methods.OrderByDescending(m => m.GetChangingMethodsCount()).ThenByDescending(m => m.GetChangingClassesCount());

Upvotes: 2

Related Questions