Language: C#
Paging with LINQ
/// <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>TSource< 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>TSource< 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); }
Tags:
Report Abuse
Subscribe
Discuss
What's new
What is it
New Snippet
Recent Snippets
My Snippets
Web Code
Search

