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

自闭症网瘾萝莉.ら 提交于 2019-12-23 13:16:14

问题


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.



来源:https://stackoverflow.com/questions/10539525/do-i-need-2-comparert-for-sorting-in-both-directions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!