从Total和PerPage值确定页数

8 c# pagination

确定您提供的数据页数的最优雅方式(在C#中)是什么:

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

目前我所拥有的是工作,但它使用if/else来检查该值是否超过总数(1页)或更多,然后必须截断小数位,执行mod操作并添加1以上如果有尾随小数.

我确信有一个数学函数可以为我做很多这样的事情,并不是那么难看.

谢谢.

Wel*_*bog 21

int pages = ((totalRecords-1) / recordsPerPage)+1
Run Code Online (Sandbox Code Playgroud)

假设totalRecords并且recordsPerPage是整数.如果它们是双打的(为什么它们会加倍?)你需要首先将它们转换为int或long,因为这依赖于整数除法.

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

public int countPages(int totalRecords, int recordsPerPage) {
  return ((totalRecords-1) / recordsPerPage)+1;
}
Run Code Online (Sandbox Code Playgroud)

如果totalRecords可以为零,则可以在函数中轻松添加特殊情况:

public int countPages(int totalRecords, int recordsPerPage) {
  if (totalRecords == 0) { return 1; }
  return ((totalRecords-1) / recordsPerPage)+1;
}
Run Code Online (Sandbox Code Playgroud)