黑马程序员技术交流社区

标题: C#分页类 [打印本页]

作者: aisini    时间: 2014-8-14 15:47
标题: C#分页类
  1. using System.Linq;
  2. using System.Collections.Generic;

  3. namespace CommonLibrary
  4. {
  5.     public class PagedList<T> : List<T>
  6.     {
  7.         #region Properties

  8.         public int PageIndex { get; private set; }

  9.         public int PageSize { get; private set; }

  10.         public int TotalCount { get; private set; }

  11.         public int TotalPages { get; private set; }

  12.         public bool HasPreviousPage
  13.         {
  14.             get { return (PageIndex > 0); }
  15.         }
  16.         public bool HasNextPage
  17.         {
  18.             get { return (PageIndex + 1 < TotalPages); }
  19.         }

  20.         #endregion

  21.         #region Constructors

  22.         public PagedList(IQueryable<T> source, int pageIndex, int pageSize)
  23.         {
  24.             if (source == null || source.Count() < 1)
  25.                 throw new System.ArgumentNullException("source");

  26.             int total = source.Count();
  27.             this.TotalCount = total;
  28.             this.TotalPages = total / pageSize;

  29.             if (total % pageSize > 0)
  30.                 TotalPages++;

  31.             this.PageSize = pageSize;
  32.             this.PageIndex = pageIndex;
  33.             this.AddRange(source.Skip(pageIndex * pageSize).Take(pageSize).ToList());
  34.         }

  35.         public PagedList(IList<T> source, int pageIndex, int pageSize)
  36.         {
  37.             if (source == null || source.Count() < 1)
  38.                 throw new System.ArgumentNullException("source");

  39.             TotalCount = source.Count();
  40.             TotalPages = TotalCount / pageSize;

  41.             if (TotalCount % pageSize > 0)
  42.                 TotalPages++;

  43.             this.PageSize = pageSize;
  44.             this.PageIndex = pageIndex;
  45.             this.AddRange(source.Skip(pageIndex * pageSize).Take(pageSize).ToList());
  46.         }

  47.         public PagedList(IEnumerable<T> source, int pageIndex, int pageSize, int totalCount)
  48.         {
  49.             if (source == null || source.Count() < 1)
  50.                 throw new System.ArgumentNullException("source");

  51.             TotalCount = totalCount;
  52.             TotalPages = TotalCount / pageSize;

  53.             if (TotalCount % pageSize > 0)
  54.                 TotalPages++;

  55.             this.PageSize = pageSize;
  56.             this.PageIndex = pageIndex;
  57.             this.AddRange(source);
  58.         }

  59.         #endregion
  60.     }
  61. }
复制代码







欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2