Using .Net how do I use the Sort method to sort an Array in reverse i.e. Z to A?
views:
207answers:
3
+3
A:
You need to pass a IComparer object or Comparison delegate to the Sort function.
Here is a sample code from C# 2.0
Array.Sort(array,delegate(string a, string b)
{
return b.CompareTo(a);
});
EDIT: missed the array bit.
Michał Piaskowski
2008-10-30 23:04:14
Why not simply return b.CompareTo(a)?
Chris Marasti-Georg
2008-10-30 23:09:54
Yeah, that's better.
Michał Piaskowski
2008-10-30 23:14:01
There are actually two important differences here:1) What should happen to null strings? Often when reversing comparisons you *don't* want to reverse what happens to nulls. Just a thought. 2) Returning -a.CompareTo(b) (i.e. pre-edit) causes problems if int.MinValue is returned by a.CompareTo(b).
Jon Skeet
2008-10-31 07:16:40
I'm pretty sure most string sorting algorithms, like this one, would throw NullReferenceExceptions if there is a null value in the list. However, the point you bring up in #1 remains for empty strings.
Chris Marasti-Georg
2008-10-31 11:28:03
+11
A:
Provide an appropriate element comparer. What C# version do you use? 3 lets you do this:
Array.Sort(myarray, (a, b) => b.CompareTo(a));
Konrad Rudolph
2008-10-30 23:05:14
+1
A:
if you use a different comparitor that is the reverse of the standard that would do it.
Alternatively sort it normally and then reverse it...
Omar Kooheji
2008-10-30 23:07:56