我特别考虑的是如何在使用c#或Java等语言时显示分页控件。

如果我有x个项目,我想在每页y块中显示,需要多少页?


当前回答

这应该能给你想要的。你肯定想要每页x个项目除以y个项目,问题是当出现不平衡的数字时,所以如果有一个部分页面,我们也想增加一页。

int x = number_of_items;
int y = items_per_page;

// with out library
int pages = x/y + (x % y > 0 ? 1 : 0)

// with library
int pages = (int)Math.Ceiling((double)x / (double)y);

其他回答

你可以使用

(int)Math.Ceiling(((decimal)model.RecordCount )/ ((decimal)4));

我做以下,处理任何溢出:

var totalPages = totalResults.IsDivisble(recordsperpage) ? totalResults/(recordsperpage) : totalResults/(recordsperpage) + 1;

并使用这个扩展,如果有0结果:

public static bool IsDivisble(this int x, int n)
{
           return (x%n) == 0;
}

此外,对于当前的页码(没有被问到,但可能有用):

var currentPage = (int) Math.Ceiling(recordsperpage/(double) recordsperpage) + 1;

这应该能给你想要的。你肯定想要每页x个项目除以y个项目,问题是当出现不平衡的数字时,所以如果有一个部分页面,我们也想增加一页。

int x = number_of_items;
int y = items_per_page;

// with out library
int pages = x/y + (x % y > 0 ? 1 : 0)

// with library
int pages = (int)Math.Ceiling((double)x / (double)y);

在CPU级别上,转换为浮点数和返回浮点数似乎是一种巨大的时间浪费。

伊恩·尼尔森的解决方案:

int pageCount = (records + recordsPerPage - 1) / recordsPerPage;

可以简化为:

int pageCount = (records - 1) / recordsPerPage + 1;

AFAICS,它没有Brandon DuRette指出的溢出错误,并且因为它只使用一次,所以您不需要存储recordsPerPage,特别是如果它来自一个从配置文件或其他东西获取值的昂贵函数。

例如,这可能是低效的,如果配置。Fetch_value使用了数据库查找之类的:

int pageCount = (records + config.fetch_value('records per page') - 1) / config.fetch_value('records per page');

这会创建一个你并不真正需要的变量,这可能有(轻微的)内存影响,并且输入太多:

int recordsPerPage = config.fetch_value('records per page')
int pageCount = (records + recordsPerPage - 1) / recordsPerPage;

这都是一行,只获取一次数据:

int pageCount = (records - 1) / config.fetch_value('records per page') + 1;

需要扩展方法:

    public static int DivideUp(this int dividend, int divisor)
    {
        return (dividend + (divisor - 1)) / divisor;
    }

这里没有支票(溢出,DivideByZero等),如果你喜欢,可以随意添加。顺便说一下,对于那些担心方法调用开销的人来说,像这样的简单函数无论如何都可能被编译器内联,所以我不认为这是需要担心的地方。欢呼。

附注:你可能会发现意识到这一点也很有用(它得到余数):

    int remainder; 
    int result = Math.DivRem(dividend, divisor, out remainder);