1: using System;
2: using System.Linq;
3:
4: namespace System.Collections.Generic
5: {
6:
7: public interface IPagedList
8: {
9: int TotalPages { get; }
10: int TotalCount { get; }
11: int PageIndex { get; }
12: int PageSize { get; }
13: bool HasPreviousPage { get; }
14: bool HasNextPage { get; }
15: bool IsFirstPage { get; }
16: bool IsLastPage { get; }
17: }
18:
19: public class PagedList<T> : List<T>, IPagedList
20: {
21:
22: public PagedList( IEnumerable<T> source, int index, int pageSize )
23: {
24:
25: //### set source to blank list if source is null to prevent exceptions
26: if( source == null )
27: source = new List<T>();
28:
29: //### set properties
30: this.TotalCount = source.Count();
31: this.PageSize = pageSize;
32: this.PageIndex = index;
33: if( this.TotalCount > 0 )
34: this.TotalPages = (int)Math.Ceiling( (double)this.TotalCount / (double)this.PageSize );
35: else
36: this.TotalPages = 0;
37: this.HasPreviousPage = ( this.PageIndex > 1 );
38: this.HasNextPage = ( this.PageIndex < this.TotalPages );
39: this.IsFirstPage = ( this.PageIndex == 1 );
40: this.IsLastPage = ( this.PageIndex == this.TotalPages );
41:
42: //### argument checking
43: if( index < 1 || index > this.TotalPages )
44: throw new ArgumentOutOfRangeException( "PageIndex out of range." );
45: if( pageSize < 1 )
46: throw new ArgumentOutOfRangeException( "PageSize cannot be less than 1." );
47:
48: //### add items to internal list
49: if( this.TotalCount > 0 )
50: this.AddRange( source.Skip( ( index - 1 ) * pageSize ).Take( pageSize ).ToList() );
51:
52: }
53:
54: public int TotalPages { get; private set; }
55: public int TotalCount { get; private set; }
56: public int PageIndex { get; private set; }
57: public int PageSize { get; private set; }
58: public bool HasPreviousPage { get; private set; }
59: public bool HasNextPage { get; private set; }
60: public bool IsFirstPage { get; private set; }
61: public bool IsLastPage { get; private set; }
62:
63: }
64:
65: public static class Pagination
66: {
67: public static PagedList<T> ToPagedList<T>( this IEnumerable<T> source, int index, int pageSize )
68: {
69: return new PagedList<T>( source, index, pageSize );
70: }
71: }
72:
73: }