The Rantings of a .NET developer in a Web 2.0 world.

C#

Paging an IEnumerable collection using one easy method

If you’re looking for a way to easily display an IEnumerable collection in a paged format, I have below a rather simple extension method that I wrote to do the job.

public static IEnumerable GetPage(this IEnumerable collection,
                                     int pageIndex,
                                     int pageSize)
{
    return collection.Skip((pageIndex - 1) * pageSize).Take(pageSize);
}

Now, what this method is essentially doing is utilizing the Skip and Take LINQ extension methods to create a new IEnumerable collection containing the paged result. It does this by first figuring out how many elements it needs to skip over based on the page index and size, and then takes the next pageSize-th elements. The nice thing about this is since we are using the Take method, if the page size is greater than the number of elements on the on the last page, it will just simply return the remaining elements with no fuss.

So let’s say we have a collection named “foo” of 320 elements and we want to show them off 30 elements at a time. To grab the first page of the collection, we simply only need to call:

foo.GetPage(1,30); //Returns the first 30 elements.

And as for elements further down in the collection, simply increment the page index:

foo.GetPage(2,30); //Returns the second set 30 elements.
foo.GetPage(3,30); //Returns the third set 30 elements.
foo.GetPage(11,30); //Returns the last 20 elements of the collection,
                    //as it is 10 shy of filling 11 pages of 30 completely.
foo.GetPage(12,30); //Returns zero elements as we are now skipping over
                    //all of the elements at the given page size.

It’s very simple to use, and even easier enough to implement and I hope it makes dealing with collection paging in your code all the more enjoyable.