CodePaste Logo
New Snippet New Snippet Recent Snippets Recent Snippets My Snippets My Snippets Web Code Search Snippets Search
Sign inor Register
Language: C#

Paging with LINQ

298 Views
Copy Code Show/Hide Line Numbers
/// <summary>
/// Returns a page worth of items from the specified collection.
/// </summary>
/// <typeparam name="TSource">the type of the items in the collection</typeparam>
/// <param name="source">an IEnumerable&gt;TSource&lt; of items to page</param>
/// <param name="pageNumber">the number of the page to return</param>
/// <param name="itemsPerPage">the number of items that make up a page</param>
/// <returns>
/// An IEnumerable&gt;TSource&lt; the contains the specified number of items for the specified pageNumber. 
/// If pageNumber exceeds the number of available pages, the returned collection will be empty.
/// </returns>
IEnumerable<TSource> GetPage<TSource>(IEnumerable<TSource> source, int pageNumber, int itemsPerPage)
{
    if (pageNumber < 1) pageNumber = 1;         // could throw an exception instead
    if (itemsPerPage < 1) itemsPerPage = 10;    // could throw an exception instead
    return source.Skip((pageNumber - 1) * itemsPerPage).Take(itemsPerPage);
}
by Al Gonzalez
  March 15, 2010 @ 9:59am
Tags:

Add a comment


Report Abuse
brought to you by:
West Wind Techologies



If you find this site useful and use it frequently please consider making a donation to support this free service.
Donate