Calculating item offset for pagination

前端 未结 9 2087
眼角桃花
眼角桃花 2020-12-12 20:53

this seems like very simple maths but somehow, my brain cant think ...

i am trying to implement pagination and will need to calculate the item offset to use in limi

9条回答
  •  有刺的猬
    2020-12-12 20:57

    Thought I would add the following for displaying text like e.g:

    Viewing 21-30 of 32 items.

    In this example:

    itemsPerPage = 10
    page = 3
    totalItems = 32
    

    And there would be a total of 4 pages where the last page only has 2 items to display. The following worked for me:

    (page  - 1) * itemsPerPage + 1 + "-" +
         Math.Min((page - 1) * itemsPerPage + itemsPerPage , totalItems ) + " of " +
         totalItems + " items."
    

    Sorry that is in C# strictly but the idea should be clear. Math.Min(x, y) returns the lower number of two parameters. There is probably an easier solution to calculate the upper bound without using Math.Min.

提交回复
热议问题