抵消foreach循环

时间:2011-11-28 11:06:33

标签: c# dictionary foreach paging

我想实现简单的分页。

我目前有一个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++;
}

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

5 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:3)

假设第一页=第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个项目集合,即使没有对字典进行任何更改。实际上,这似乎不会发生。但是,不要指望将字典的任何添加内容添加到最后一页,例如。

答案 2 :(得分:1)

您可以使用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);
}

答案 3 :(得分:1)

使用LINQ的Skip()Take()

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

答案 4 :(得分:1)

如果你不想迭代一些元素只是为了找到相关索引的某些元素,那么将你的项目从字典中移出并转换为可索引的东西可能是值得的,也许是List<KeyValuePair>(显然创建列表将迭代字典的所有元素,但可能只执行一次)。

然后可以这样使用:

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];
}