CodePaste Logo
New Snippet New Snippet Recent Snippets Recent Snippets My Snippets My Snippets Web Code Search Snippets Search
Sign inor Register
Language: C#

Generic comparer

158 Views
Copy Code Show/Hide Line Numbers
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
by darek156
  April 01, 2010 @ 1:47am
Tags:

Add a comment


Report Abuse
brought to you by:
West Wind Techologies



If you find this site useful and use it frequently please consider making a donation to support this free service.
Donate