using System; using System.Collections; using System.Collections.Generic; namespace ChanSort { /// /// The DelegateComparer class is used as an adapter to use a simple delegate method in places /// where an IComparer interface is expected /// public class DelegateComparer : IComparer { private readonly Func handler; private readonly bool reverse; /// /// Create a new DelegateComparer /// /// The method used to compare two objects public DelegateComparer(Func handler) { this.handler = handler; } public DelegateComparer(Func handler, bool reverse) : this(handler) { this.reverse=reverse; } /// /// Compares two objects by delegating the request to the handler-delegate /// public int Compare(object o1, object o2) { int r=this.handler(o1, o2); return this.reverse ? -r : +r; } } public class DelegateComparer : IComparer, IComparer { private readonly Func handler; private readonly bool reverse; public DelegateComparer(Func handler, bool reverse = false) { this.handler = handler; this.reverse = reverse; } public int Compare(T x, T y) { var r = handler(x, y); return reverse ? -r : r; } int IComparer.Compare(object x, object y) => this.Compare((T) x, (T) y); } }