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?
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));
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With