Skip to content

Instantly share code, notes, and snippets.

@mahizsas
Forked from lurumad/PaginatedList
Last active August 29, 2015 14:13
Show Gist options
  • Save mahizsas/a9dd9158db57a25a5bfb to your computer and use it in GitHub Desktop.
Save mahizsas/a9dd9158db57a25a5bfb to your computer and use it in GitHub Desktop.
Paged list with C#
using System;
using System.Collections.Generic;
using System.Linq;
using MongoDB.Driver;
namespace Luru.Collections
{
public class PaginatedList<T>
{
public int PageIndex { get; set; }
public int PageSize { get; set; }
public int TotalCount { get; set; }
public int TotalPages { get; set; }
public List<T> Items { get; set; }
public bool HasNextPage
{
get { return PageIndex < TotalPages; }
}
public bool HasPreviousPage
{
get { return PageIndex > 1; }
}
public PaginatedList()
{
}
public PaginatedList(IQueryable<T> source, int pageIndex, int pageSize)
{
var skip = (PageIndex - 1) * PageSize;
PageIndex = pageIndex;
PageSize = pageSize;
TotalCount = source.Count();
TotalPages = (int)Math.Ceiling(TotalCount / (double)PageSize);
Items = source.Skip(skip).Take(pageSize).ToList();
}
public PaginatedList(MongoCursor<T> source, int pageIndex, int pageSize)
{
var skip = (PageIndex - 1) * PageSize;
PageIndex = pageIndex;
PageSize = pageSize;
Items = source.SetSkip(skip).SetLimit(pageSize).ToList();
TotalCount = (int)source.Count();
TotalPages = (int)Math.Ceiling(TotalCount / (double)PageSize);
}
public PaginatedList(IEnumerable<T> source, int pageIndex, int pageSize)
{
var skip = (PageIndex - 1) * PageSize;
PageIndex = pageIndex;
PageSize = pageSize;
var enumerable = source.ToList();
TotalCount = enumerable.Count();
TotalPages = (int)Math.Ceiling(TotalCount / (double)PageSize);
Items = enumerable.Skip(skip).Take(pageSize).ToList();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment