jeudi 17 décembre 2015

Building generic order-by-statement

I have a class with a bunch of properties/fields (I know public fields are bad practice, but they exist within our legacy-code for simple DTOs):

class Foo {
    public string Name;
    public int Age;
}

and a collection of instances of Foo.

Now I want to order those elements by a property given by the user. So the user selects a property from the type Foo. Now I want to order by elements based on this property.

One approach is a reflection-based one similar to this:

var p = typeof(Foo).GetProperty("Age");
var ordered = fooList.OrderBy(x => (int) p.GetValue(x, null));

This works so far. However I also tried a second one and there I am stuck. It deals by performing an expression-tree as follows:

var f = GetOrderStatement<Foo>("Age");
var ordered = fooList.OrderBy(f)

With

Func<T, int> GetOrderStatement<T>(string attrName)
{
    var type = Expression.Parameter(typeof(T), attrName);
    var property = Expression.PropertyOrField(type, attrName);
    return Expression.Lambda<Func<T, int>>(property).Compile();
}

My question is: As I should return a Func<T, int> where to get the int-part from or in other words where and how do I perform the actual comparison? I suppose I have to make a CallExpression to IComparable.CompareTo but I´m not sure how to do so.





Aucun commentaire:

Enregistrer un commentaire