106

I have an array and I want to divide them into page according to preset page size.

This is how I do:

private int CalcPagesCount()
{
    int  totalPage = imagesFound.Length / PageSize;

    // add the last page, ugly
    if (imagesFound.Length % PageSize != 0) totalPage++;
    return totalPage;
}

I feel the calculation is not the simplest (I am poor in math), can you give one simpler calculation formula?

Vadim Ovchinnikov
  • 13,327
  • 5
  • 62
  • 90
Benny
  • 8,547
  • 9
  • 60
  • 93
  • imo, what feels "ugly" is not the fact that u have an "if", but the fact that your firstly calculated "totalPage" is not the actual total number of pages, and u have to "patch" it in a complementary calculus. See my answer below which only adds semantic code. – Tristan Mar 19 '21 at 09:47

13 Answers13

229

Force it to round up:

totalPage = (imagesFound.Length + PageSize - 1) / PageSize;

Or use floating point math:

totalPage = (int) Math.Ceiling((double) imagesFound.Length / PageSize);
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • 2
    Danger ... this results in an overflow when `PageSize = int.MaxValue`. I added an answer that's not vulnerable to an overflow. – Jeremy Nov 11 '17 at 15:03
  • 12
    To avoid the overflow you could just refactor the formula to get: `((imagesFound.Length - 1) / PageSize) + 1` – AdrianRM Jan 21 '19 at 16:15
34

NOTE: you will always get at least 1 page, even for 0 count, if the page size is > 1, which is what I needed but may not be what you need. A page size of 1(silly but technically valid) and a count of 0 would be zero pages. Depending on your needs you may want to check for a zero value for count & page size of 1

int pages = ((count - 1) / PAGESIZE) + 1;
Booji Boy
  • 4,522
  • 4
  • 40
  • 45
  • Yes, simpler. Simpler but Wrong. if count = 0 then pages = 1 – Pavel Melnikov Aug 04 '17 at 15:04
  • 1
    @Pevel Melnikov . I suppose in a purely pedantic sense it is wrong, but it depends on context. In the code I used this in I always wanted at least 1 page (0 pages was invalid even if there were 0 items). I should at least add a note. – Booji Boy Aug 14 '17 at 19:46
  • 3
    @PavelMelnikov, it's not exactly wrong. Just depends on how you want to look at it. The assumption that it always returns at least 1 page is incorrect, though. 0 records and a page size of 1 will result in 0. So just either not allow a page size of 0 or do a check. – Michael Jan 09 '18 at 23:47
24

Actually, you are close to the best you can do. About the only thing that I can think of that might be "better" is something like this:

totalPage = (imagesFound.Length + PageSize - 1) / PageSize;

And the only reason that this is any better is that you avoid the if statement.

Tom
  • 776
  • 1
  • 5
  • 12
  • Danger ... this results in an overflow when `PageSize = int.MaxValue`. I added an answer that's not vulnerable to an overflow. – Jeremy Nov 11 '17 at 15:03
13

The OP contains a valid answer. If I wanted to turn off paging then I could set PageSize = int.MaxValue.

Several answers here add to PageSize (imagesFound.Length + PageSize) and that could cause an overflow. Which then leads to an incorrect result.

This is the code I am going to use:

int imageCount = imagesFound.Length;

// include this if when you always want at least 1 page 
if (imageCount == 0)
{
    return 1;
}

return imageCount % PageSize != 0 
    ? imageCount / PageSize + 1 
    : imageCount / PageSize;
Jeremy
  • 587
  • 6
  • 12
  • Or use something like my answer to avoid all the clutter to essentially be doing the same thing here. single line of code that calculates this exact multi-conditional statement. – Clayton C Oct 26 '22 at 14:33
6

Always used this formula:

int totalPages = items.Count / pageSize + (items.Count % pageSize > 0 ? 1 : 0);
just_dev
  • 61
  • 1
  • 1
4
var pageCount = (int)Math.Ceiling((float)_collection.Count / (float)_itemsPerPage);

Explanation:

Divide the number of items in the collection by the items per page. Then use Math.Ceiling to round this number up to the nearest integer.

e.g. 7 Items in the 'Book' / 3 items per page = 2.33. 2.33 rounded up to the nearest int = 3.

2

just semantic code, which makes explicit the partial result, and makes it obvious for any reader what is calculated. I prefer this to the compact formula :

    private int calculateNbPages(int nbResults, int pageSize)
        {
            int  nbFullyFilledPages = nbResults / pageSize;
            int nbPartiallyFilledPages = (nbResults % pageSize == 0) ? 0 : 1;
            
            return nbFullyFilledPages + nbPartiallyFilledPages;
        }
Tristan
  • 8,733
  • 7
  • 48
  • 96
1

To avoid having errors with page numbering the best way I can think of calculating noOfPages is by doing the following line

totalPage = Math.Ceiling(imagesFound.Length / PageSize);

This should not give you page 2 when PageSize == imagesFound.Length

Clayton C
  • 531
  • 1
  • 4
  • 19
  • 1
    I don't think this is valid. If you have a length of 3 and a pagesize of 2, you would expect 2 pages (first page has 2 items, second page has 1). Doing this will give you (3-1)/2 = 1 page. – joshhendo Sep 01 '15 at 00:23
  • Altered the original post to accommodate for that aswell, thanks for noticing – Clayton C Apr 11 '16 at 09:07
1
  1. You Can Get Total Page in Sql Server:-
DECLARE @PageCount INT;
DECLARE @NoOfData INT;
SET @NoOfData = (select Count(*) AS [PageCount] from YourTableName)
SET @PageCount=((@NoOfData+@PageSize-1)/@PageSize)
SELECT @PageCount AS [PageCount]
  1. You Can get in your code-
int totalPage = (int) Math.Ceiling((double) imagesFound.Length / PageSize);

1

Following worked for me:

if(totalRecords%value === 0){
  count = (totalRecords) / value;
}
else {
  count = Math.floor((totalRecords + value - 1) / value);
}
QauseenMZ
  • 1,081
  • 8
  • 6
0

Something I wrote myself:

private int GetPageCount(int count, int pageSize)
{
    int result = 0;

    if(count > 0)
    {
        result = count / pageSize;
        if(result > 0 && (count > (pageSize * result)))
        {
           result++;
        }
    }

    return result;
}

(And sure, don't set pageSize to int.MaxValue)

st_stefanov
  • 1,147
  • 1
  • 10
  • 28
0

Below is working code to calculate pagination in List:

              int i = 0;
              int pagecount = 0;
              int pageSize = 50;

List Items= new List (); To do : Add items in List:

              if (Items.Count() != 0)
              {
                    int pageNumber = Total Records / 50;

                          for (int num = 0; numi < pageNumber; num++)
                          {
                                var x = Items.Skip(i * pageSize).Take(pageSize);
                                i++;
                          }

                    var y = Items.Skip(i * pageSize).Take(pageSize);
              }
0

I used the function below. It does not use floating point calculation, so it is faster than some other solutions I have seen.

int GetPageCount()
{
    //when pageSize is 0, return all records on one page
    return (pageSize != 0) ? (recordCount / pageSize + Math.Sign(recordCount % pageSize)) : 1;
}
panpawel
  • 1,782
  • 1
  • 16
  • 17