Linq分页排序通用方法

1.通用方法     2.调用

-----------------------------1.-------------------------------------------

public class CommonRepository<T> where T : class,new()
{
/// <summary>
/// LinQ分页查询
/// </summary>
/// <param name="source">条件查询之后的List</param>
/// <param name="sortExpression">排序字段</param>
/// <param name="sortDirection">排序方式</param>
/// <param name="pageIndex">页码</param>
/// <param name="pageSize">页数</param>
/// <param name="totalCount">总数</param>
/// <returns></returns>
public IQueryable<T> GetPageListForLinQ(IQueryable<T> source, string sortExpression, string sortDirection, int pageIndex, int pageSize)
{
string sortingDir = string.Empty;
if (sortDirection.ToUpper().Trim() == "ASC")
{
sortingDir = "OrderBy";
}
else
{
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<T> query = source.AsQueryable().Provider.CreateQuery<T>(expr);
return query.Skip((pageIndex - 1) * pageSize).Take(pageSize);
}

----------------------------------------2.-------------------------------------------------

CommonRepository<APIResponsePatientSearchLatelyList> commonRepository = new CommonRepository<APIResponsePatientSearchLatelyList>();

SqlParameter sqlParametersList = new SqlParameter() {   .....................      };

string querySql="select * From table where coloms=@a";

var list = db.Database.SqlQuery<APIResponsePatientSearchLatelyList>(querySql, sqlParametersList);

IQueryable<APIResponsePatientSearchLatelyList> pageList = commonRepository.GetPageListForLinQ(list.AsQueryable<APIResponsePatientSearchLatelyList>(),
"pid", ConstHelper.ORDERBY_DESC, pageIndex, pageSize);

posted @ 2019-06-25 10:10  dandan00056  阅读(382)  评论(0编辑  收藏  举报