Last active
March 31, 2021 14:56
-
-
Save chrcar01/b7524b46686338a1bd7b70248369ea45 to your computer and use it in GitHub Desktop.
GenericComparer<T>
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class GenericComparer<T> : IComparer<T> | |
{ | |
private readonly Func<T, IComparable> _comparer; | |
private GenericComparer(Func<T, IComparable> comparer) | |
{ | |
_comparer = comparer ?? throw new ArgumentNullException(nameof(comparer)); | |
} | |
public static GenericComparer<T> Create(Func<T, IComparable> comparer) | |
{ | |
return new GenericComparer<T>(comparer); | |
} | |
public int Compare(T? x, T? y) | |
{ | |
if (x == null && y == null) return 0; | |
if (x == null) return -1; | |
if (y == null) return 1; | |
return _comparer(x).CompareTo(_comparer(y)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment