public static IQueryable<T> ApplySort<T>(this IQueryable<T> source, string sort)
{
if (source == null)
{
throw new ArgumentNullException("source");
}
if (sort == null)
{
return source;
}
var lsSort = sort.Split(',');
// run through the sorting options and create a sort expression string from them
string completeSortExpression = "";
foreach (var sortOption in lsSort)
{
// if the sort option starts with "-", we order descending, otherwise ascending
if (sortOption.StartsWith("-"))
{
completeSortExpression = completeSortExpression + sortOption.Remove(0, 1) + " descending,";
}
else
{
completeSortExpression = completeSortExpression + sortOption + ",";
}
}
if (!string.IsNullOrWhiteSpace(completeSortExpression))
{
source = source.OrderBy(completeSortExpression.Remove(completeSortExpression.Count() - 1));
}
return source;
}
public static class QueryableHelper
{
public static IQueryable<TModel> OrderBy<TModel>(this IQueryable<TModel> q, string name)
{
Type entityType = typeof(TModel);
PropertyInfo p = entityType.GetProperty(name);
MethodInfo m = typeof(QueryableHelper).GetMethod("OrderByProperty").MakeGenericMethod(entityType, p.PropertyType);
return (IQueryable<TModel>)m.Invoke(null, new object[] { q, p });
}
public static IQueryable<TModel> OrderByDescending<TModel>(this IQueryable<TModel> q, string name)
{
Type entityType = typeof(TModel);
PropertyInfo p = entityType.GetProperty(name);
MethodInfo m = typeof(QueryableHelper).GetMethod("OrderByPropertyDescending").MakeGenericMethod(entityType, p.PropertyType);
return (IQueryable<TModel>)m.Invoke(null, new object[] { q, p });
}
public static IQueryable<TModel> OrderByPropertyDescending<TModel, TRet>(IQueryable<TModel> q, PropertyInfo p)
{
ParameterExpression pe = Expression.Parameter(typeof(TModel));
//Expression se = Expression.Convert(Expression.Property(pe, p), typeof(object));
Expression se = Expression.Convert(Expression.Property(pe, p), typeof(TRet));
return q.OrderByDescending(Expression.Lambda<Func<TModel, TRet>>(se, pe));
}
public static IQueryable<TModel> OrderByProperty<TModel, TRet>(IQueryable<TModel> q, PropertyInfo p)
{
ParameterExpression pe = Expression.Parameter(typeof(TModel));
//Expression se = Expression.Convert(Expression.Property(pe, p), typeof(object));
Expression se = Expression.Convert(Expression.Property(pe, p), typeof(TRet));
return q.OrderBy(Expression.Lambda<Func<TModel, TRet>>(se, pe));
}
}