tags:

views:

90

answers:

4

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.

+1  A: 
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;
}
Welbog
A: 
int totalPages = (int)Math.Ceiling((double)totalRecords/recordsPerPage);
Jason
I can just imagine the computer deciding that 50/25 = 2.0000000000096 or some such nonsense.
Brian
A: 
int pages = 1 + (totalRecords + 1) / (recordsPerPage + 1)
James M.
That doesn't work if both totalRecords and recordsPerPage are the same. It will output 2 instead of the correct 1. You shouldn't be adding one to the numerator, just the denominator.
Welbog
A: 

Problem with this approach:

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

if totalRecords is 1 results in divide by 0. Need an extra if statement.

Here is my rewrite. .NET tends to use -1 when no result is possible on an int return. So reuse this convention.

public int countPages(int totalRecords, int recordsPerPage)
{ 

//insert as many paranthesies and tabs as makes you happy.
if(totalRecords == 0) return -1;
return (totalRecords % recordsPerPage) == 0? 
(totalRecords/recordsPerPage) 
: (totalRecords/recordsPerPage) + 1; 

}
foreachdev