linq扩展方法

    xiaoxiao2021-04-04  41

    1.动态排序

    public static IQueryable<T> Sort<T>(this IQueryable<T> source, string sort) { string sortStr = ""; string sortDirection = ""; string sortDir = string.Empty; if(!string.IsNullOrEmpty(sort)) { sortStr = sort.Split('-')[0];//排序字段 sortDirection = sort.Split('-')[1];//方向 } if (sortDirection.Trim().ToUpper() == "ASC") { sortDir = "OrderBy"; } else { sortDir = "OrderByDescending"; } ParameterExpression param = Expression.Parameter(typeof(T), sortStr); PropertyInfo pi = typeof(T).GetProperty(sortStr); Type[] types = new Type[2]; types[0] = typeof(T); types[1] = pi.PropertyType; Expression expr = Expression.Call(typeof(Queryable), sortDir, types, source.Expression, Expression.Lambda(Expression.Property(param, sortStr), param)); IQueryable<T> query = source.AsQueryable().Provider.CreateQuery<T>(expr); return query; }

    2.分页

    2.1扩展基础类

    [Serializable] public class PagedList<T> : List<T> { /// <summary> /// /// </summary> /// <param name="source">数据源</param> /// <param name="pageIndex">页码,从0开始</param> /// <param name="pageSize">每页显示数量</param> public PagedList(IQueryable<T> source, int pageIndex, int pageSize) { int total = source.Count(); TotalCount = total; TotalPages = total / PageSize; if (total % pageSize > 0) { TotalPages++; } PageSize = pageSize; this.PageIndex = pageIndex; AddRange(source.Skip(pageIndex * pageSize).Take(pageSize).ToList()); } public PagedList(IEnumerable<T> source, int pageIndex, int pageSize) { int total = source.Count(); TotalCount = total; TotalPages = total / PageSize; if (total % pageSize > 0) { TotalPages++; } PageSize = pageSize; this.PageIndex = pageIndex; AddRange(source); } public PagedList(IList<T> source, int pageIndex, int pageSize) { int total = source.Count; TotalCount = total; TotalPages = total / PageSize; if (total % pageSize > 0) { TotalPages++; } PageSize = pageSize; this.PageIndex = pageIndex; AddRange(source); } /// <summary> /// 页码索引 /// </summary> public int PageIndex { get; private set; } /// <summary> /// 每页显示记录数 /// </summary> public int PageSize { get; private set; } /// <summary> /// 总记录 /// </summary> public int TotalCount { get; private set; } /// <summary> /// 总页数 /// </summary> public int TotalPages { get; private set; } /// <summary> /// 上一页? /// </summary> public bool HasPrePage { get { return (PageIndex > 0); } } /// <summary> /// 下一页 /// </summary> public bool HasNextPage { get { return (PageIndex + 1 < TotalPages); } } }

    2.2扩展方法

    public static PagedList<T> ToPagedList<T>(this IQueryable<T> soruce, int pageIndex, int pageSize) { return new PagedList<T>(soruce,pageIndex,pageSize); }

    转载请注明原文地址: https://ju.6miu.com/read-666240.html

    最新回复(0)