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开发者_如何学Python 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?
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;
});
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();
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());
精彩评论