Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need 2 Comparer<T> for sorting in both directions?

If I create a Comparer<T> for the purposes of sorting a set of objects, is there a simple way to 'invert' it so I can sort in the other direction? Or do I need to define a 2nd Comparer<T> with the tests in the Compare method swapped around?

like image 845
Stuart Hemming Avatar asked Dec 28 '22 01:12

Stuart Hemming


2 Answers

public class ReverseComparer<T> : Comparer<T>
{
    private Comparer<T> inputComparer;
    public ReverseComparer(Comparer<T> inputComparer)
    {
        this.inputComparer = inputComparer;
    }

    public override int Compare(T x, T y)
    {
        return inputComparer.Compare(y, x);
    }
}

This allows you to do something like:

list.Sort(new ReverseComparer(someOtherComparer));
like image 151
Servy Avatar answered Jan 04 '23 22:01

Servy


It's not the efficent code, but you can use Reverse after sort with the Comparer<T>:

var ordered = theList.Sort(new FooComparer()).Reverse();

Since you tagger your question .Net4
You can use LINQ OrderBy and ThenBy, so you don't need even one Comparer<T>...

var ordered = theList.OrderBy(x => x.First).ThenBy(x => x.Second);
var reverseOrdered = theList.OrderByDescending(x => x.First)
                            .ThenByDescending(x => x.Second);
like image 27
gdoron is supporting Monica Avatar answered Jan 04 '23 23:01

gdoron is supporting Monica