using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; namespace DataSort { public class DataHelper { public static IQueryable<T> Sort<T>(IQueryable<T> queryable, string sort, string order) { if (string.IsNullOrWhiteSpace(sort)) { return queryable; } var sortExpression = Expression.Parameter(queryable.ElementType); var selector = Expression.Lambda(Expression.PropertyOrField(sortExpression, sort), sortExpression); if (order.ToLower() == "asc") { return (IQueryable<T>)queryable.Provider.CreateQuery(Expression.Call(typeof(Queryable), "OrderBy", new Type[] { queryable.ElementType, selector.Body.Type }, queryable.Expression, selector)); } else if (order.ToLower() == "desc") { return (IQueryable<T>)queryable.Provider.CreateQuery(Expression.Call(typeof(Queryable), "OrderByDescending", new Type[] { queryable.ElementType, selector.Body.Type }, queryable.Expression, selector)); } return queryable; } } }