Do I need 2 Comparer for sorting in both direct

2019-06-26 01:04发布

问题:

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?

回答1:

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));


回答2:

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);


回答3:

You can use the same Comparer<T>, just when you need the result inverted you can simply use myList<T>.Reverse() method.