Determine # of pages from Total and PerPage values

c#, pagination

Solution

int pages = ((totalRecords-1) / recordsPerPage)+1

Assuming `totalRecords` and `recordsPerPage` are ints. If they're doubles (why are they doubles?) you'll need to convert them to ints or longs first, because this relies on integer division to work.

Wrap it in a function so that you don't have to repeat the calculation everywhere in your code base. Just set it up once in a function like this:

public int countPages(int totalRecords, int recordsPerPage) {
  return ((totalRecords-1) / recordsPerPage)+1;
}

If `totalRecords` can be zero, you can just add a special case for it in the function easily:

public int countPages(int totalRecords, int recordsPerPage) {
  if (totalRecords == 0) { return 1; }
  return ((totalRecords-1) / recordsPerPage)+1;
}

Problem

What is the most elegant way (in C#) of determining how many pages of data you have given: a.) Total Records b.) Records Per page. Currently what I have is working, but it's using if/else to check if the value is than the total (1 page) or more, and then has to truncate the decimal place, perform a mod operation and add 1 more if there was a trailing decimal. I'm sure there's a Math function that does alot of this for me and isn't so ugly. Thanks.

Original source