A friend of mine asked me to generate pages from a List<T>. This is my implementation:

using System;
using System.Collections.Generic;
using System.Linq;

namespace Pager
{
    static class Program
    {
        static void Main()
        {
            List<int> list = new List<int>();

            //add 26 items
            for (int x = 0; x < 26; x++)
            {
                list.Add(x);
            }

            //generate pages
            List<int>[] pagesList = Pager<int>(list, 4);

            Console.WriteLine("Please examine pagesList");
            System.Diagnostics.Debugger.Break();

        }

        /// <summary>
        /// Converts a collection of T to an array of pages
        /// </summary>
        /// <typeparam name="T">The type of items in the list, can be inferred most of the time</typeparam>
        /// <param name="list">The list to page</param>
        /// <param name="itemsPerPage">Items per page</param>
        /// <returns>An array of lists, pages if you will</returns>
        static List<T>[] Pager<T>(ICollection<T> list, int itemsPerPage)
        {
            int pages = (int)Math.Ceiling((double)list.Count / itemsPerPage);

            List<T>[] pagesList = new List<T>[pages];

            for (int currentPage = 0; currentPage < pages; currentPage++)
            {
                pagesList[currentPage] = list.Skip(currentPage * itemsPerPage).Take(itemsPerPage).ToList();
            }

            return pagesList;
        }
    }
}

Leave a Reply


And shepherds we shall be, for thee my Lord for thee, power hath descended forth from thy hand, that our feet may swiftly carry out thy command. We shall flow a river forth to thee, and teeming with souls shall it ever be. In nomine Patris, et Filii, et Spiritus Sancti.