I'm using a generic method to sort an IQueryable
collection which uses the Queryable.OrderBy
and LambdaExpression
methods:
public static IQueryable<T> OrderBy<T>(this IQueryable<T> source, IEnumerable<SortParameter> sortParameters)
{
IOrderedQueryable<T> sourceOrderedQueryable = sortParameters[0].SortDirection == ListSortDirection.Ascending
? Queryable.OrderBy(source, (dynamic)CreateExpression<T>(sortParameter[0].ParameterName))
: Queryable.OrderByDescending(source, (dynamic)CreateExpression<T>(sortParameter[0].ParameterName));
// ... Same with Queryable.ThenBy
return sourceOrderedQueryable;
}
private static LambdaExpression CreateExpression<T>(string propertyName)
{
var modelParameter = Expression.Parameter(typeof(T), "t");
Expression body = Expression.PropertyOrField(modelParameter, sortParameter);
return Expression.Lambda(body, modelParameter);
}
query.OrderBy(sortParameters) // for ProductId sortParameter (string type in db) should sort as int
This works fine but I have to parse one column from the sorted model from string to int, something like:
OrderBy(x => Convert.ToInt32(x.ProductId))
I have no idea how to integrate the above conversion into this generic mechanism and the lambda expression for a specific case. Is it possible for this mechanism to converting one column (property) type?