【问题标题】:How to use Skip() and Take() with IQueryable如何在 IQueryable 中使用 Skip() 和 Take()
【发布时间】:2011-09-17 09:30:50
【问题描述】:

我有一个包含转发器的用户控件,它的数据源是使用 IEnumerable 对象设置的,该对象包含从代码中的查询返回的数据。转发器具有分页功能,并为每页显示自定义数量的记录。

我不想在每次用户单击下一步按钮以查看转发器中的下一页记录时加载所有数据。如何使它成为 IQueryable 并使用 Skip() 和 Take() 仅显示该页面所需的记录?

我有以下代码:

//Code that assigns query to repeater data source
DataSet = QueryGoesHere.ToArray(); // returns IEnumerable
repeater.DataSource = DataSet;
repeater.DataBind();

//Code that creates PagedDataSource - how can I update this to make it display only the records that are needed for the currently displayed page?

            objPds = new PagedDataSource();
            objPds.DataSource = DataSource
            objPds.AllowPaging = true;
            objPds.PageSize = 5;
            objPds.CurrentPageIndex = CurrentPage;
            lblCurrentPage.Text = "Page: " + (CurrentPage + 1).ToString() + " of " + objPds.PageCount.ToString();

【问题讨论】:

    标签: c# asp.net user-controls


    【解决方案1】:

    如果我猜对了,您想使用自己的实现而不是加载所有数据然后使用 PagedDataSource 对吗?

    如果是这样,您必须确保 QueryGoesHere 是支持此功能的 Queryable(Linq2Sql 或 EF)。然后你必须像这样计算你的日期

    var count = QueryGoesHere.Count();
    

    并获取您要显示的数据部分:

    var skip = (curPageNumber - 1)*itemsPerPage;
    var display = Math.Min(count - skip, itemsPerPage);
    

    然后使用

    var displayedItems = QueryGoesHere.Skip(skip).Take(display).ToArray();
    

    这应该可以解决问题。

    【讨论】:

      【解决方案2】:

      PagedList 和相关的扩展将对您有所帮助。请参考:http://wekeroad.com/2007/12/10/aspnet-mvc-pagedlistt

      【讨论】:

        【解决方案3】:
            public static Dictionary<string, string> SampleDataList(int startIndex, int pageSize)
            {
                var sampleTable = new Dictionary<string, string>();
        
                var page = TemporaryData().Skip(startIndex).Take(pageSize);
                var query = from p in page
                            select new
                            {
                                FirstColumn = p.Key,
                                SecondColumn = p.Value
                            };
        
                foreach (var row in query)
                    sampleTable.Add(row.FirstColumn, row.SecondColumn);
        
                return sampleTable;
            }
        

        以下链接将帮助您了解如何使用中继器进行分页

        http://cmsnsoftware.blogspot.com/2011/07/how-to-use-custom-pagination.html

        【讨论】:

        • skip 应该在take 之前,不是吗?
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-10-03
        • 2015-04-28
        • 2019-10-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-02-03
        相关资源
        最近更新 更多