mic*_*ael 2 c# linq collections pagination
我有一个项目集合: ICollection<T> MyCollection
我想知道是否有办法获得项目的子集(分页)而不会超过最后一页...现在它返回一个空列表,因为我继续经过可用的页面.
例如,如果MyCollection
有10个项目并且我要求第5页(每页3个项目),我会得到一个空集合.相反,我真的想要最后一页(恰好是第4页,1项).不知道该怎么做.如果有一种LINQ方式可以实现这一目标.
示例变量:
int page = 5;
int itemPerPage = 3;
//MyCollection.Count == 10;
Run Code Online (Sandbox Code Playgroud)
逻辑:
// make sure there are any items and that itemsPerPage is greater than zero
// to prevent any DivideByZeroExeceptions from being thrown
if (MyCollection.Any() && itemsPerPage > 0)
{
if (page * itemsPerPage > MyCollection.Count)
{
// if page is past collection change to the last page
page = (int)Math.Ceiling((float)MyCollection.Count / (float)itemsPerPage);
}
else if (page < 1)
{
// if page is before collection change to 1
page = 1;
}
// skip pages and select the number of pages
MyCollection.Skip((page - 1) * itemsPerPage).Take(itemsPerPage);
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下,page = 5
它位于集合之外,(5 * 3 == 12)
因此页面将重置为10 divided and rounded up by 3 == 4
.最后它将跳过(4 - 1) * 3 == 9
然后取3
,这将是包含1
项目的最后一页
我通常把这个分而治的逻辑放到一个整数扩展方法中:
public static class IntExtensions
{
public static int DivideByAndRoundUp(this int number, int divideBy)
{
return (int)Math.Ceiling((float)number / (float)divideBy);
}
}
Run Code Online (Sandbox Code Playgroud)
这会让你写 page = MyCollection.Count.DivideAndRoundUp(itemsPerPage)