【问题标题】:Get a page from a collection without going past the last page?从集合中获取页面而不经过最后一页?
【发布时间】:2011-10-07 17:57:36
【问题描述】:

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

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

例如,如果MyCollection 有 10 个项目,我要求第 5 页(每页 3 个项目)我得到一个空集合。相反,我真的想要最后一页(恰好是第 4 页,第 1 项)。不知道在这里做什么。如果有一种 LINQ 方式可以做到这一点,那会很震撼。

【问题讨论】:

    标签: c# linq collections pagination


    【解决方案1】:

    示例变量:

    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) 之外,因此页面将重置为 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)

    【讨论】:

    • @Jason - 你认为这是做什么的:page * itemsPerPage &gt; MyCollection.Count17 * 3 &gt; 10 然后page = 10 ~/ 3 = 4 这是最后一页
    【解决方案2】:

    “纯”LINQ:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-04
      • 1970-01-01
      相关资源
      最近更新 更多