I am trying to sort an IQueryable object dynamically (using reflection in order to locate the requested ordering field) and I have followed the approach below, where I essentially use extension methods on the queryable and then dynamically build the Lambda to be used for the sorting
public static class IQueryableOrderingExtensions
{
public static IOrderedQueryable<T> OrderBy<T>(this IQueryable<T> source, string propertyName)
{
return source.OrderBy(ToExpression<T>(propertyName));
}
public static IOrderedQueryable<T> OrderByDescending<T>(this IQueryable<T> source, string propertyName)
{
return source.OrderByDescending(ToExpression<T>(propertyName));
}
private static Expression<Func<T, object>> ToExpression<T>(string propertyName)
{
var parameter = Expression.Parameter(typeof(T));
var property = Expression.Property(parameter, propertyName);
UnaryExpression propAsObject = null;
if (property.Type.IsEnum)
{
//TODO
}
else
{
propAsObject = Expression.Convert(property, typeof(object));
}
return Expression.Lambda<Func<T, object>>(propAsObject, parameter);
}
}
The issue I am facing has to do with Enums, that by default are being treated as integers when sorting. Example (Waiting Approval = 0, Approved = 1 etc.)
I there a way to achieve this? Is there a way to map the property to something like property.ToString?