Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class ByKeyComparer<T, TKey> : IComparer<T>
- {
- private readonly Func<T, TKey> _keySelector;
- private readonly IComparer<TKey> _keyComparer;
- public ByKeyComparer(Func<T, TKey> keySelector, IComparer<TKey> keyComparer = null)
- {
- if (keySelector == null) throw new ArgumentNullException("keySelector");
- _keySelector = keySelector;
- _keyComparer = keyComparer ?? Comparer<TKey>.Default;
- }
- public int Compare(T x, T y)
- {
- return _keyComparer.Compare(_keySelector(x), _keySelector(y));
- }
- }
- public class CompositeComparer<T> : IComparer<T>
- {
- private readonly IEnumerable<IComparer<T>> _comparers;
- public CompositeComparer(IEnumerable<IComparer<T>> comparers)
- {
- if (comparers == null) throw new ArgumentNullException("comparers");
- _comparers = comparers.ToList().AsReadOnly();
- }
- public IEnumerable<IComparer<T>> Comparers
- {
- get { return _comparers; }
- }
- public CompositeComparer(params IComparer<T>[] comparers)
- : this((IEnumerable<IComparer<T>>)comparers)
- {
- }
- public int Compare(T x, T y)
- {
- foreach (var comparer in _comparers)
- {
- int result = comparer.Compare(x, y);
- if (result != 0)
- return result;
- }
- return 0;
- }
- }
- public class ReverseComparer<T> : IComparer<T>
- {
- private readonly IComparer<T> _comparer;
- public ReverseComparer(IComparer<T> comparer)
- {
- _comparer = comparer;
- }
- public int Compare(T x, T y)
- {
- return _comparer.Compare(y, x);
- }
- }
- public static class ByKeyComparer<T>
- {
- public static IComparer<T> CompareBy<TKey>(Func<T, TKey> keySelector, IComparer<TKey> keyComparer = null)
- {
- return new ByKeyComparer<T, TKey>(keySelector, keyComparer);
- }
- public static IComparer<T> CompareByDescending<TKey>(Func<T, TKey> keySelector, IComparer<TKey> keyComparer = null)
- {
- return new ByKeyComparer<T, TKey>(keySelector, keyComparer).Reverse();
- }
- }
- public static class ComparerExtensions
- {
- public static IComparer<T> Reverse<T>(this IComparer<T> comparer)
- {
- return new ReverseComparer<T>(comparer);
- }
- public static IComparer<T> ThenBy<T>(this IComparer<T> comparer, IComparer<T> otherComparer)
- {
- var composite = comparer as CompositeComparer<T>;
- if (composite != null)
- return new CompositeComparer<T>(composite.Comparers.Concat(new[] { otherComparer }));
- return new CompositeComparer<T>(comparer, otherComparer);
- }
- public static IComparer<T> ThenBy<T, TKey>(this IComparer<T> comparer, Func<T, TKey> keySelector, IComparer<TKey> keyComparer = null)
- {
- return comparer.ThenBy(ByKeyComparer<T>.CompareBy(keySelector, keyComparer));
- }
- public static IComparer<T> ThenByDescending<T, TKey>(this IComparer<T> comparer, Func<T, TKey> keySelector, IComparer<TKey> keyComparer = null)
- {
- return comparer.ThenBy(ByKeyComparer<T>.CompareByDescending(keySelector, keyComparer));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement