Reputation: 8407
What is the best and nicest solution to find the page for a value in a list that is for example paged by 10.
So I have int 0-1000
. I page by 10
. So 23
will be at page 3
.
Who has got a nice solution?
Upvotes: 0
Views: 70
Reputation: 6511
No need to round, and then use ceiling. Integer division will do a floor, then just add 1.
int page = ndx / 10 + 1;
or for a generic number of pages:
int page = ndx / perPage + 1
If your first item is 1, you just need to add one to the index
int page = (ndx + 1) / perPage + 1
Upvotes: 2
Reputation: 15242
Int pageNumber = (Int) Math.Ceiling(((Double) (item.Index + 1) / (Double) itemsPerPage));
This is assuming that you know what item you are looking for and that the list doesn't start at 0, if it does then add one to the index.
I'm going to expaund on this answer since people seem to be having trouble with it. Also I corrected for starting at 0.
In C# integer division returns as such
anything that is a fraction part is floored or rounded down, so simply doing integer division on the items index and the number of items in a page.
For the below explanation consider that the numerator is (index + 1)
23 / 10 = 2
, which isn't true, since the item is on the third page. Adding 1 to the answer doesn't solve the problem since 20 / 10 = 2 + 1 = 3 which isn't correct since this item is on the 2nd page.
By casting to double's we cause double division to happen
double / double
returns a double
. Then taking the Ceiling of that rounds up giving us the page we are on.
Upvotes: 3