Do I need 2 Comparer<T> for sorting in both directions?
.net-4.0, c#, sorting
Solution
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));
Problem
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?