score:2

Accepted answer

Actually, it fails for Age too:

Expression of type 'System.Int32' cannot be used for return type 'System.Object'

The immediate issue is that you need a conversion (a box in this case) from a value-type to an object:

var mySortExpression = Expression.Lambda<Func<ObjectToOrder, object>>(
    Expression.Convert(
        Expression.Property(param, field),
        typeof(object)
    ), param);

However, using object here could in-and-of-itself be problematic. I suggest looking at Dynamic LINQ OrderBy on IEnumerable<T>


Related Articles