How to build () => x.prop lambda expression dynamically?

Andrej Slivko picture Andrej Slivko · Jan 27, 2011 · Viewed 24.3k times · Source

I have code like

DepartmentPaperConsumption dto = null;

then later i have NHibernate QueryOver result, and i want to order it

result.OrderByAlias(() => dto.TotalColorCopys);

but I want to be able to specify any property of dto dynamicly with string. I tryed using Dynamic LINQ but is seems that I just can't get it. I also tried building LambdaExpression from ground up - also without luck. I would appreciate any help.

Answer

Marc Gravell picture Marc Gravell · Jan 27, 2011

You can see how to construct the lambda here, but it really is pretty simple in your case:

var arg = Expression.Constant(null, typeof(DepartmentPaperConsumption));
var body = Expression.Convert(Expression.PropertyOrField(arg, propertyName),
    typeof(object));
var lambda = Expression.Lambda<Func<object>>(body);

The tricky thing is invoking the OrderByAlias - using MakeGenericMethod may be the way, as shown in the link above.