Skip to content

Instantly share code, notes, and snippets.

@chrcar01
Last active March 31, 2021 14:56
Show Gist options
  • Save chrcar01/b7524b46686338a1bd7b70248369ea45 to your computer and use it in GitHub Desktop.
Save chrcar01/b7524b46686338a1bd7b70248369ea45 to your computer and use it in GitHub Desktop.
GenericComparer<T>
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