Generic expression IComparer

This provides a generic IComparer using Linq expressions, the aim of the ExpressionComparer<T> is allow you sort collections or arrays of classes through its properties.

The constructor of the expression comparer receives a:

params Func<T, IComparable>[] expressions

Which represents the properties of each element inside the collection or array. One important thing is that the properties used by the comparer needs to implement IComparable interface.

The implementation of the Compare method is very simple, it just iterate over the expressions array and compares each property in both objects:

public int Compare(T x, T y)

{

    foreach (var expression in _expressions)

    {

        int result = Compare(

            expression.Invoke(x), expression.Invoke(y));

        if (result != 0)

            return result;

    }

    return 0;

}

private int Compare(IComparable x, IComparable y)

{

    if (x == null && y == null)

        return 0;

    if (x == null)

        return -1;

    if (y == null)

        return 1;

    return x.CompareTo(y);

}

In order to use de ExpressionComparer<T> you have to instance the class sending the expressions to compare, for example if you want to sort a list of products by cost and price:

List<Product> productList = new List<Product>

{

    new Product { ProductId = 1, Name = "Diskette 3.5\"",

        Price = 10, Cost = 9 },

    new Product { ProductId = 2, Name = "Diskette 5.25\"",

        Price = 5, Cost = 4 },

    new Product { ProductId = 3, Name = "Monitor 19\"",

        Price = 200, Cost = 150 },

    new Product { ProductId = 4, Name = "Monitor 17\"",

        Price = 199, Cost = 151 },

    new Product { ProductId = 4, Name = "Monitor 15\"",

        Price = 198, Cost = 150 }

};

productList.Sort(

    new ExpressionComparer<Product>(p => p.Cost, p => p.Price));

I posted a full sample here.

No Comments