Search code examples
c#dictionaryforeachpagination

Offset foreach loop


I want to implement simple paging.

I currently have a Dictionary and display its contents on a page by iterating through it with a foreach loop.
I could not find a way to offset a foreach loop.

Let's say I have 100 items. 5 items per page, which makes 20 pages in total. I'll start with the following:

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

This would be outputting the first page correctly - now how do I display the subsequent pages?


Solution

  • Assuming first page = page 1:

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

    Note that technically this isn't foolproof since, as http://msdn.microsoft.com/en-us/library/xfhwa508.aspx states:

    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.

    Thus it is theoretically possible for the same request for the first 10 items to return a different set of 10 items, even without any changes to the dictionary. In practical terms, this doesn't seem to occur. But don't expect any additions to the dictionary to be added to the last page, for example.