Blog

Filter posts by Category Or Tag of the Blog section!

A Paging Helper as an extension

Sunday, 01 October 2017

There are lots of libraries out there to use paging in enterprise applications. I personally would prefer to write my own as it’s customizable and easy to maintain and modify. Look at the following Generic 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 int FirstRowOnPage

        {



            get { return (CurrentPage - 1) * PageSize + 1; }

        }



        public int LastRowOnPage

        {

            get { return Math.Min(CurrentPage * PageSize, RowCount); }

        }



        public IList<T> Results { get; set; }



        public PagedResult()

        {

            Results = new List<T>();

        }

    }


 

Now, in order to create an extension method for paging, consider the following one: 

 

 public static class PagingExtension

    {

        const int pageSize = 20;



        public static PagedResult<T> GetPaged<T>(this IQueryable<T> query, int page) 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 it, in order to use the above extension method: 
 


   public PagedResult<Coin> GetCoins(int page, bool active,int userId)

        {

            var activeExpression = GetActiveCoinExpression(active);

            return _context.Set<Coin>()

                .Include(x => x.UserFavouriteCoins.Where(x => x.UserId == userId))

                .Where(activeExpression).GetPaged(page);

        }


 

Forget about the extra codes of the above method but the using GetPaged(page) !

Category: Software

Tags: C#

comments powered by Disqus