在不超过最后一页的情况下从集合中获取一页



我有一个项目集合:ICollection<T> MyCollection

我想知道是否有一种方法可以在不经过最后一页的情况下获得项目(页面)的子集合…现在它返回一个空列表,因为我一直在浏览可用的页面。

例如,如果MyCollection有10个项目,我请求第5页(每页3个项目),我得到一个空集合。相反,我真正想要的是最后一页(恰好是第4页,第1项)。不知道该怎么做。如果LINQ能做到这一点,那就太棒了。

变量示例:

int page = 5;
int itemPerPage = 3;
//MyCollection.Count == 10;

逻辑:

// 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);
}

在本例中,page = 5位于集合(5 * 3 == 12)之外,因此page被重置为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);
    }
}

可以写page = MyCollection.Count.DivideAndRoundUp(itemsPerPage)

"Pure" LINQ:

var result = (arr.Count > (page - 1) * perPage ? 
            arr.Skip(perPage * (page - 1)) : 
                arr.Skip(arr.Count / perPage * perPage))
                .Take(perPage);

最新更新