I use one such:
public class AnonymousComparer<T> : IComparer<T>
{
private Comparison<T> comparison;
public AnonymousComparer(Comparison<T> comparison)
{
if (comparison == null)
throw new ArgumentNullException("comparison");
this.comparison = comparison;
}
public int Compare(T x, T y)
{
return comparison(x, y);
}
}
Using:
var carComparer = new AnonymousComparer<Car>((x, y) => x.Name.CompareTo(y.Name));
If you are doing a direct comparison of properties, and the type of the property implements IComparable(for example, intor string), then I also have this class, which is a bit more concise in use:
public class PropertyComparer<T, TProp> : IComparer<T>
where TProp : IComparable
{
private Func<T, TProp> func;
public PropertyComparer(Func<T, TProp> func)
{
if (func == null)
throw new ArgumentNullException("func");
this.func = func;
}
public int Compare(T x, T y)
{
TProp px = func(x);
TProp py = func(y);
return px.CompareTo(py);
}
}
Using this:
var carComparer = new PropertyComparer<Car, string>(c => c.Name);
source
share