using System; using System.Linq; using System.Linq.Expressions; using System.Reflection; namespace BLL { public static class SortConditionHelper { public static IQueryable DataSorting(IQueryable source, string sortExpression, string sortDirection) { string sortingDir = string.Empty; if (sortDirection.ToUpper().Trim() == "ASC") sortingDir = " OrderBy "; else if (sortDirection.ToUpper().Trim() == "DESC") sortingDir = " OrderByDescending "; ParameterExpression param = Expression.Parameter(typeof(T), sortExpression); PropertyInfo pi = typeof(T).GetProperty(sortExpression); Type[] types = new Type[2]; types[0] = typeof(T); types[1] = pi.PropertyType; Expression expr = Expression.Call(typeof(Queryable), sortingDir, types, source.Expression, Expression.Lambda(Expression.Property(param, sortExpression), param)); IQueryable query = source.AsQueryable().Provider.CreateQuery(expr); return query; } public static IQueryable DataPaging(IQueryable source, int pageNumber, int pageSize) { return source.Skip(pageNumber * pageSize).Take(pageSize); } public static IQueryable SortingAndPaging(IQueryable source, string sortExpression, string sortDirection, int pageNumber, int pageSize) { IQueryable query = DataSorting(source, sortExpression, sortDirection); return DataPaging(query, pageNumber, pageSize); } } }