【问题标题】:Offset foreach loop偏移 foreach 循环
【发布时间】:2012-01-07 20:33:18
【问题描述】:

我想实现简单的分页。

我目前有一个 Dictionary,并通过使用 foreach 循环遍历它来在页面上显示其内容。
我找不到抵消foreach 循环的方法。

假设我有 100 件商品。每页5个项目,总共20页。我将从以下内容开始:

int counter = 0;
int itemsPerPage = 5;
int totalPages = (items.Count - 1) / itemsPerPage + 1;
int currentPage = (int)Page.Request.QueryString("page"); //assume int parsing here
Dictionary<string, string> currentPageItems = new Dictionary<string, string>;

foreach (KeyValuePair<string, string> item in items) //items = All 100 items
{
    //---Offset needed here----
    currentPageItems.Add(item.Key, item.Value);
    if (counter >= itemsPerPage)
        break;
    counter++;
}

这将正确输出首页 - 现在如何显示后续页面?

【问题讨论】:

    标签: c# dictionary foreach paging


    【解决方案1】:

    借助 LINQ,您可以使用SkipTake 轻松实现分页。

    var currentPageItems = items.Skip(itemsPerPage * currentPage).Take(itemsPerPage);
    

    【讨论】:

      【解决方案2】:

      假设第一页 = 第 1 页:

      var currentPageItems =
          items.Skip(itemsPerPage * (currentPage - 1)).Take(itemsPerPage)
          .ToDictionary(z => z.Key, y => y.Value);
      

      请注意,技术上这并非万无一失,因为正如http://msdn.microsoft.com/en-us/library/xfhwa508.aspx 所说:

      For purposes of enumeration, each item in the dictionary is treated as a KeyValuePair(Of TKey, TValue) structure representing a value and its key. The order in which the items are returned is undefined.

      因此,理论上可能对前 10 个项目的相同请求返回一组不同的 10 个项目,即使没有对字典进行任何更改。实际上,这似乎不会发生。但是不要指望字典中的任何添加都会添加到最后一页。

      【讨论】:

      • 我喜欢你的解释和你的.ToDictionary 分机。另外,您在这里比其他人更需要声誉:-)
      • @moontear - 很好,我喜欢你接受了信誉得分最低的人的回答。好主意。
      【解决方案3】:

      您可以使用 Linq SkipTake 扩展方法来做到这一点...

      using System.Linq
      
      ...
      
      var itemsInPage = items.Skip(currentPage * itemsPerPage).Take(itemsPerPage)
      foreach (KeyValuePair<string, string> item in itemsInPage) 
      {
          currentPageItems.Add(item.Key, item.Value);
      }
      

      【讨论】:

        【解决方案4】:

        使用 LINQ 的 Skip()Take()

        foreach(var item in items.Skip(currentPage * itemsPerPage).Take(itemsPerPage))
        {
            //Do stuff
        }
        

        【讨论】:

          【解决方案5】:

          如果您不希望迭代某些元素只是为了获得一些相关索引,则可能值得将您的项目从字典中移出并放入可索引的内容中,也许是 List&lt;KeyValuePair&gt;(显然创建list 将遍历字典的所有元素,但可能只能这样做一次)。

          然后可以像这样使用:

          var dictionary = new Dictionary<string, string>();
          var list = dictionary.ToList();
          
          var start = pageNumber*pageSize;
          var end = Math.Min(list.Count, start + pageSize);
          for (int index = start; index++; index < end)
          {
              var keyValuePair = list[index];
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2018-01-08
            • 2012-07-01
            • 1970-01-01
            • 2013-09-29
            • 2019-03-01
            • 2017-06-14
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多