Saturday, October 3, 2015

Class for paging for generic collections

Import namespaces

using System.Collections;
using System.Collections.Generic;
using System.Linq;

Class for paging

public class PagingCollection : IEnumerable
{
    #region fields
    private const int DefaultPageSize = 10;
    private readonly IEnumerable _collection;
    private int _pageSize = DefaultPageSize;
    #endregion

    #region properties
    /// 
    /// Gets or sets page size
    /// 
public int PageSize { get { return _pageSize; } set { if (value <= 0) { throw new ArgumentException(); } _pageSize = value; } } /// /// Gets pages count /// public int PagesCount { get { return (int)Math.Ceiling(_collection.Count() / (decimal)PageSize); } } #endregion #region ctor /// /// Creates paging collection and sets page size /// public PagingCollection(IEnumerable collection, int pageSize) { if (collection == null) { throw new ArgumentNullException("collection"); } PageSize = pageSize; _collection = collection.ToArray(); } /// /// Creates paging collection /// public PagingCollection(IEnumerable collection) : this(collection, DefaultPageSize) { } #endregion #region public methods /// /// Returns data by page number /// public IEnumerable GetData(int pageNumber) { if (pageNumber < 0 || pageNumber > PagesCount) { return new T[] { }; } int offset = (pageNumber - 1) * PageSize; return _collection.Skip(offset).Take(PageSize); } /// /// Returns number of items on page by number /// public int GetCount(int pageNumber) { return GetData(pageNumber).Count(); } #endregion #region static methods /// /// Returns data by page number and page size /// public static IEnumerable GetPaging(IEnumerable collection, int pageNumber, int pageSize) { return new PagingCollection(collection, pageSize).GetData(pageNumber); } /// /// Returns data by page number /// public static IEnumerable GetPaging(IEnumerable collection, int pageNumber) { return new PagingCollection(collection, DefaultPageSize).GetData(pageNumber); } #endregion #region IEnumerable Members /// /// Returns an enumerator that iterates through collection /// public IEnumerator GetEnumerator() { return _collection.GetEnumerator(); } #endregion #region IEnumerable Members /// /// Returns an enumerator that iterates through collection /// IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } #endregion }

Use

// fill test data
var data = new List<int>();
for (int i = 0; i < 25; i++)
{
    data.Add(i);
}

// create paging collection
var paging = new PagingCollection<int>(data);
// set page size
paging.PageSize = 6;

// get number of pages
Console.WriteLine("Pages count: {0}", paging.PagesCount);

// iterate through pages
for (int i = 1; i <= paging.PagesCount; i++)
{
    // get number of items on page
    Console.WriteLine("Page: {0} ({1} items)", i, paging.GetCount(i));

    // get data by page number
    foreach (int number in paging.GetData(i))
    {
        Console.WriteLine(number);
    }
}

0 Comments:

Post a Comment