Tools

Generic pagination in C# for .NET WebAPI

A generic C# class to provide plug and play JSON list paging

cnpagedlist-code

"I love writing pagination code!"...said no one ever. After what seems like the millionth time writing a list pager from scratch, we've come up with a handy generic class to plug in for .NET API projects. And by "we" I mean my colleague J2, I just use it a lot. 

The idea is really simple, and it's not a lot of code, but it's guaranteed to save you time in your next .NET WebAPI project. It's built with Entity Framework in mind, but it will work with any IQueryable collection. We use IQueryable because at the time of pagination, you should not have executed your query yet in most cases. Otherwise you would be fetching the full list of items before just returning a few of them, rather than fetching only those few to begin with. Of course if you need to fetch the whole list (to perform a calculation on each result perhaps) you can do that as well and simply cast the list AsQueryable() when you pass it to the pager.

The CNPagedList constructor takes in an IQueryable collection, an optional page number, and an optional page size. The class will then be serialized into a JSON response when returned from an API endpoint and will contain the requested items along with the current page, current page size, and the total count of the collection for use in calling the next page of results.

Here is an example JSON response of a CNPagedList object:

{
  "items": [
    {
      "name":"Item 1"
    },
    {
      "name":"Item 2"
    },
    {
      "name":"Item 3"
    }
  ],
  "page": 1,
  "pageSize":3,
  "totalItemCount":10
}

All you need to do to use this class is to copy the file into your solution (don't forget to adjust the namespace) and set your API controller method to return the type CNPagedList<T> replacing the generic T with the actual class type of the list of items you're paging over. The return a new instance of CNPagedList as the response.


public CNPagedList<Site> SiteList(string q=null, int? pageLimit=null, int? page=null)
{
	pageLimit = pageLimit ?? 25;

	//SiteService is a repository for communicating with the database
	SiteService service = new SiteService(db);
	var sites = service.GetSiteList(q);

	return new CNPagedList<Site>(sites, page, pageLimit);
}

It's as easy as that. One important thing to note is that whenever you're doing pagination, you need to perform a sort (OrderBy) on the IQuerable list before you page it. That's because page 2 of a list of items sorted by ID is much different than page 2 of a list of items sorted by Date.

The code is available over on Github: CypressNorth/.NET-CNPagedList

I hope someone else finds this simple solution as helpful as we have.

ITWorld DealPost: The best in tech deals and discounts.
Shop Tech Products at Amazon