Easily paginate collections in C#
In this post, we’ll create two extensions that lets us easily paginate any collection in C#.
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);
}
With this, all IQueryable
and IEnumerable
instances automatically gets 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.