C# 根据总页数和每页值确定页数

C# 根据总页数和每页值确定页数,c#,pagination,C#,Pagination,确定您提供了多少页数据的最优雅的方法(C#)是什么: a、 )总记录 b、 )每页记录 目前我所做的工作正在进行,但它使用if/else检查值是否大于总数(1页)或更多,然后必须截断小数点,执行mod操作,如果有尾随小数点,则再添加1 我确信有一个数学函数可以为我做很多这方面的事情,而且也不那么难看 谢谢 int pages = ((totalRecords-1) / recordsPerPage)+1 假设totalRecords和recordsPerPage为整数。如果它们是双精度的(为什

确定您提供了多少页数据的最优雅的方法(C#)是什么:

a、 )总记录 b、 )每页记录

目前我所做的工作正在进行,但它使用if/else检查值是否大于总数(1页)或更多,然后必须截断小数点,执行mod操作,如果有尾随小数点,则再添加1

我确信有一个数学函数可以为我做很多这方面的事情,而且也不那么难看

谢谢

int pages = ((totalRecords-1) / recordsPerPage)+1
假设
totalRecords
recordsPerPage
为整数。如果它们是双精度的(为什么是双精度的?)

将其包装在函数中,这样就不必在代码库中的任何地方重复计算。只需在如下函数中设置一次:

public int countPages(int totalRecords, int recordsPerPage) {
  return ((totalRecords-1) / recordsPerPage)+1;
}
如果
totalRecords
可以为零,您只需在函数中为其添加一个特例即可:

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

这种方法的问题是:

public int countPages(int totalRecords, int recordsPerPage) {  
    if (totalRecords == 0) { return 1; }  return ((totalRecords-1) / recordsPerPage)+1;
}
如果totalRecords为1,则结果为除以0。需要一个额外的if语句

这是我的重写。当int返回结果不可能时,NET倾向于使用-1。所以重复使用这个约定

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; 

}

我可以想象计算机决定50/25=2.0000000000096或者类似的胡说八道。如果totalRecords和recordsPerPage都是相同的,那就行不通了。它将输出2而不是正确的1。你不应该在分子上加一,而应该在分母上加一(totalRecords无需测试
totalRecords==0
的情况,因为
-1
除以
recordsPerPage
会四舍五入到
0
,只要
recordsPerPage
大于
1
,通常情况下都是这样。这不会导致除以0的错误。这只可能是
>recordsPerPage
为0。
public int countPages(int totalRecords, int recordsPerPage) {  
    if (totalRecords == 0) { return 1; }  return ((totalRecords-1) / recordsPerPage)+1;
}
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; 

}