Language: C#
Generic comparer
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); } } //Usage: var carComparer = new AnonymousComparer<Car>((x, y) => x.Name.CompareTo(y.Name)); //If you're doing a straight property compare and the property type implements IComparable (for example an int or string), //then, I also have this class which is a bit more terse to 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); } } //Usage: var carComparer = new PropertyComparer<Car, string>(c => c.Name); //http://stackoverflow.com/questions/2557894/what-is-the-best-way-to-have-a-generic-comparer
Tags:
Report Abuse
Subscribe
Discuss
What's new
What is it
New Snippet
Recent Snippets
My Snippets
Web Code
Search

