Sorting Arrays

  • Thread starter Thread starter Durand
  • Start date Start date
D

Durand

Hi all,

I am using a sort method from Array class to order in ascending way. What
can I do to descending way using same sort method?

Thanks

Durand
 
Durand said:
I am using a sort method from Array class to order in ascending way. What
can I do to descending way using same sort method?

Either use an IComparator instance which gives the reverse of the
normal sort order (if you already have an IComparator, you could very
easily write an IComparator which just returned the reverse of whatever
that comparator would return) or sort the array first and then call
Array.Reverse.
 
Wim Hollebrandse said:
IComparator in Java, IComparer interface in C#...

Oops - just Comparator in Java, in fact :)

Serves me right for not checking though - which I'd have done if I'd
given a sample for how to write a reversing IComparer. Just for
reference, here it is:

using System;
using System.Collections;

public class ReversingComparer : IComparer
{
IComparer original;

public ReversingComparer (IComparer original)
{
if (original==null)
{
throw new ArgumentNullException ("original");
}
this.original = original;
}

public int Compare (object x, object y)
{
return -original.Compare (x, y);
}
}
 
Thanks all, it woks!

Jon Skeet said:
Oops - just Comparator in Java, in fact :)

Serves me right for not checking though - which I'd have done if I'd
given a sample for how to write a reversing IComparer. Just for
reference, here it is:

using System;
using System.Collections;

public class ReversingComparer : IComparer
{
IComparer original;

public ReversingComparer (IComparer original)
{
if (original==null)
{
throw new ArgumentNullException ("original");
}
this.original = original;
}

public int Compare (object x, object y)
{
return -original.Compare (x, y);
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top