2011-11-28 109 views
3

我想实现简单的分页。偏移foreach循环

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

这将输出第一页正确的 - 现在我怎么显示后续页面?

回答

2

假设第一页=第1页:

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

注意技术上这个ISN因为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个项目,即使没有任何改变到词典中。实际上,这似乎不会发生。但是,例如,不要指望将任何新增的字典添加到最后一页。

+0

我喜欢你的解释,你的'.ToDictionary'扩展。另外你需要的声誉比其他人在这里:-) –

+0

同情投票!哇噢! :) – mjwills

+0

@moontear - 不错的一个,我喜欢你接受最低信誉评分的人的答案。好想法。 – ColinE

3

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

var currentPageItems = items.Skip(itemsPerPage * currentPage).Take(itemsPerPage); 
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); 
} 
1

使用LINQ的Skip()Take()

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

@downvoter:小心解释为什么? –

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