Easily paginate collections in C#

In order to apply paging to collections, I find it useful to use the following extension methods:

   public static IEnumerable<TSource> Page<TSource>(this IEnumerable<TSource> source, int? page, int pageSize)
   {
      return source.Skip((page ?? 0) * pageSize).Take(pageSize);
   }

   public static IQueryable<TSource> Page<TSource>(this IQueryable<TSource> source, int? page, int pageSize)
   {
      return source.Skip((page ?? 0) * pageSize).Take(pageSize);
   }

By adding them to an extension class within a certain namespace, all IQueryable and IEnumerable objects automatically receives paging functionality. You will then be able to write (for instance):

   List<string> strings = new List<string> { "a","b","c","d","e","f" };
   strings.Page(2, 2);

And get a list that contains “c” and “d”.

Man, I really must start using a code tool, so that  I do not have to hack the code manually when writing these blogs  😛

Advertisements