新建一个类,名为PagedList,继承List<T>
Code
1 public class PagedList<T> : List<T>
2 {
3 /// <summary>
4 /// 分页编号
5 /// </summary>
6 public int PageIndex { get; set; }
7
8 /// <summary>
9 /// 分页大小
10 /// </summary>
11 public int PageSize { get; set; }
12
13 /// <summary>
14 /// 元素总共数目
15 /// </summary>
16 public int TotalCount { get; set; }
17
18 /// <summary>
19 /// 页数
20 /// </summary>
21 public int PageCount { get; set; }
22
23 /// <summary>
24 /// 构造函数
25 /// </summary>
26 /// <param name="list">链表</param>
27 /// <param name="intPageIndex">编号</param>
28 /// <param name="intPageSize">大小</param>
29 public PagedList(List<T> list, int intPageIndex, int intPageSize)
30 {
31 PageIndex = intPageIndex;
32 PageSize = intPageSize;
33
34 GetPagedList(list);
35 }
36
37 /// <summary>
38 /// 转为为分页
39 /// </summary>
40 /// <param name="list">链表</param>
41 private void GetPagedList(List<T> list)
42 {
43 int intStart = (PageIndex - 1) * PageSize;
44
45 for (int i = intStart; i < intStart + PageSize && i < list.Count; i++ )
46 {
47 this.Add(list[i]);
48 }
49
50 TotalCount = list.Count;
51 PageCount = TotalCount / PageSize + 1;
52 }
53 }
再新建一个类,名为PagedListExpansion
Code
public static class PagedListExpansion
{
public static PagedList<T> ToPagedList<T>(this List<T> list, int intPageIndex, int intPageSize)
{
return new PagedList<T>(list, intPageIndex, intPageSize);
}
}
这样一个简单分页类就完成了。
调用为:
Code
List<int> list = new List<int>();
PagedList<int> page = list.ToPagedList<int>(1, 10);
这样的分页类可以对所有的类型的链表都通用了,这只是个启发性Demo,有什么错请指出来,有更好的办法,记得提出来。