There are a bunch of open source library for paging In C# but sometimes you need to have your own paging engine to have more control over. I've used the following simple custom paging in a few projects. Look at the following class:
public class PagedResult<T> where T : class
{
public int CurrentPage { get; set; }
public int PageCount { get; set; }
public int PageSize { get; set; }
public int RowCount { get; set; }
public IList<T> Results { get; set; }
public PagedResult()
{
Results = new List<T>();
}
}
All of we needs in simple paging is there. Now let's do soma calculation for our paging in an extension class which is the goal of this post as well:
public static class Extension
{
public static PagedResult<T> GetPagedResult<T>(this IQueryable<T> query, int page, int pageSize) where T : class
{
var result = new PagedResult<T>
{
CurrentPage = page,
PageSize = pageSize,
RowCount = query.Count()
};
var pageCount = (double)result.RowCount / pageSize;
result.PageCount = (int)Math.Ceiling(pageCount);
var skip = (page - 1) * pageSize;
result.Results = query.Skip(skip).Take(pageSize).ToList();
return result;
}
}
That's all! In order to use the above extension method, look at the sample below:
class Program
{
static void Main(string[] args)
{
var pagedResult = GenerateData().GetPagedResult<Post>(1, 20);
}
static IQueryable<Post> GenerateData()
{
var posts = new List<Post>();
for (int i = 0; i < 100; i++)
{
posts.Add(new Post { Id = i, Title = string.Format("title of {0}", i.ToString()) });
}
return posts.AsQueryable();
}
class Post
{
public int Id { get; set; }
public string Title { get; set; }
}
}