A generic C# class to provide plug and play JSON list paging
"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:
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
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
[ Take this mobile device management course from PluralSight and learn how to secure devices in your company without degrading the user experience. ]
I hope someone else finds this simple solution as helpful as we have.