Generic Comparer
Have you ever had to write a comparer for a specific type, only to be frustrated when you needed to write a second and third comparer for other types? Fear not, a generic comparer can take care of this for you!
/// <summary>
/// Compares two objects of any type.
/// </summary>
/// <typeparam name="T">The type to be compared.</typeparam>
public class GenericComparer<T> : IComparer<T>
{
// The compare method
private readonly Func<T, T, int> _compareMethod = null;
/// <summary>
/// The constructor.
/// </summary>
/// <param name="compareMethod">The compare method.</param>
public GenericComparer(Func<T, T, int> compareMethod)
{
// Sanitize
if (compareMethod == null)
{
throw new ArgumentNullException("compareMethod");
}
_compareMethod = compareMethod;
}
/// <summary>
/// Compares two objects.
/// </summary>
/// <param name="x">The first object.</param>
/// <param name="y">The second object.</param>
/// <returns>Less than 0 if x is less than y, greater than
/// 0 if x is greater than y, 0 if they are equal.</returns>
public int Compare(T x, T y)
{
return _compareMethod(x, y);
}
}
Just pass a method to the constructor that takes 2 objects of type T and returns an int, and you’re all set!