Easily paginate collections in C#

Aug 27, 2009 · Follow on Twitter and Mastodon archive

This post looks at how to easily paginate collections in C#, which can be easily achieved with two very basic extensions.

When paginating a collection in C#, I find the following extensions useful:

public static IEnumerable<TSource> Paginate<TSource>(this IEnumerable<TSource> source, int? page, int pageSize)
{
    return source.Skip((page ?? 0) * pageSize).Take(pageSize);
}
public static IQueryable<TSource> Paginate<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 instances will automatically receives this functionality:

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

The pagination code above will return a list that contains “c” and “d”.

Discussions & More

Please share any ideas, feedback or comments you may have in the Disqus section below, or by replying on Twitter or Mastodon..

If you found this text interesting, make sure to follow me on Twitter and Mastodon for more content like this, and to be notified when new content is published.

If you like & want to support my work, please consider sponsoring me on GitHub Sponsors.