What is the best way to have a common Comparer

I have many comparison classes, where the compared class simply checks the property of the object name and compares the strings. For instance:

public class ExerciseSorter : IComparer<Exercise>
{
    public int Compare(Exercise x, Exercise y)
    {
        return String.Compare(x.Name, y.Name);
    }
}

public class CarSorter : IComparer<Car>
{
    public int Compare(Car x, Car y)
    {
        return String.Compare(x.Name, y.Name);
    }
}

What is the best way to create this code, so I don't need to write redundant code again and again.

+3
source share
3 answers

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);
+8
source

.NET 4.5, , Comparison<T> IComparer<T> .

Create Comparer<T> class, Comparison<T> Comparer<T> ( IComparer<T>).

, :

// Sample comparison, any T will do.
Comparison<int> comparison = (x, y) => x.CompareTo(y)

// Get the IComparer.
IComparer<T> comparer = Comparer.Create(comparison);

-, IComparer<T>, Comparison<T> (, Sort List<T> class).

+1

If all your classes have a Name property, you can enter an interface IHaveNameand create such a mapper:

public class NameComparer : IComparer<IHaveName>
{
    public int Compare(IHaveName x, IHaveName y)
    {
        return String.Compare(x.Name, y.Name);
    }
}
0
source

Source: https://habr.com/ru/post/1739414/


All Articles