tags:

views:

51

answers:

2

I've just written a couple of pagination extension methods and I was curious to know if there was any improvements I could make.

I'm pretty happy with the base pagination method, where you supply both the page size and page number (as seen below)

    public static IEnumerable<T> Paginate<T>(this IEnumerable<T> source, int pageSize, int pageNumber)
    {
        if (pageSize == 0) throw new ArgumentOutOfRangeException("pageSize");
        if (pageNumber == 0) throw new ArgumentOutOfRangeException("pageNumber");

        return source.Skip(pageSize * (pageNumber - 1)).Take(pageSize);
    }

but I was wondering if there was a better way to do the "auto" pagination, where it returns a IEnumerable<IEnumerable<T>>

    public static IEnumerable<IEnumerable<T>> Paginate<T>(this IEnumerable<T> source, int pageSize)
    {
        source.ThrowIfNull("source");
        if (pageSize == 0) throw new ArgumentOutOfRangeException("pageSize");

        var pageCount = (int)Math.Ceiling(source.Count() / (double)pageSize);

        if (pageSize == 1)
            pageCount = source.Count();

        for (int i = 1; i <= pageCount; i++)
        {
            yield return source.Paginate(pageSize, i);
        }
    }

It seems a bit suspect to have to iterate twice (once for the count and once for the yield return.

Is there any obvious way I could improve these methods?

+3  A: 

Take a look at MoreLinq Batch :- http://code.google.com/p/morelinq/source/browse/trunk/MoreLinq/Batch.cs?r=84

Hightechrider
Having at look at those Batch methods, I genuinely can't work out how they work O.o Thanks for the link though, looks like a great library!
Alastair Pitts
A: 

The answers to this question:

http://stackoverflow.com/questions/1349491/how-can-i-split-an-ienumerablestring-into-groups-of-ienumerablestring/3935352#3935352

are all different ways of paginating.

diceguyd30