Click here to Skip to main content
15,886,796 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have employed List.Sort after reading that it's algorithm is not only much easier to use but also faster than my own sorting techniques.

The benchmarks prove this true, but there is one thing that is stopping me from committing to using this method:

When the comparison is equal, the sort order is switched any way. I am not sure if this is my own fault or if it is part of the design.

My code is shown below.

// Sort friends by rating (0 - 3)
 onlineFriends.Sort(delegate(Friend f1, Friend f2) { return f2.Rating.CompareTo(f1.Rating); });

// If f1.Rating is 0 and f2.Rating is 0, they may swap places anyway
Posted

I wouldn't have expected this behaviour... :confused:
Why don't you just write in more sorting criteria then? Even if you can assign them all indexes or something. Just run your second lot of sorting criteria if the two are equally rated. That's what I'd do.
 
Share this answer
 
Comments
Derek R. White 28-Jun-10 22:38pm    
I agree. I am going to make the name of the friend be the second sort criteria. I suppose it's more organized anyway.
dawmail333 28-Jun-10 22:56pm    
Always err on the side of more organization, we need it somewhere ;)
I believe it's because of the QuickSort implementation that's internally used. This is a bit of a hack, but you could do this:

C#
friends.Sort(delegate(Friend f1, Friend f2) { return f2.Rating.CompareTo(f1.Rating) >= 0 ? 1 : -1; });
 
Share this answer
 
Comments
Derek R. White 28-Jun-10 22:23pm    
I was trying something like this, but it keeps saying there is an invalid argument. When I start debugging, it says that f1 is null. When I check to make sure f1 or f2 are not null, it is still telling me there is an invalid argument. Your method doesn't give this error, but only because you allow 0 to be a value. I am trying to force -1 if 0 is a value, and it doesn't like it..
Nish Nishant 28-Jun-10 22:28pm    
I think you are confusing the Rating's value with what CompareTo returns. CompareTo returns 0 when the items are identical and I am working around that to prevent it from swapping the items in that case.
Derek R. White 28-Jun-10 22:36pm    
No, when 0 is replaced by 1 it yields the same effect, so I was trying to replace it with -1, but it won't allow me to. I think I'm just going to go back to my initial method..
So to anyone who cares, this is what I ended up with:
friends.Sort(delegate(Friend f1, Friend f2) { int i = f2.Rating.CompareTo(f1.Rating); return i == 0 ? f1.FriendName.CompareTo(f2.FriendName) : i; });
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900