Tuesday, January 18, 2011

Paging for Linq

using System;
using System.Linq;


namespace WebHelpers.Extensions
{
    public static class Helpers
    {
        public static IQueryable<T> LimitAndOffset<T>(this IQueryable<T> q,      
                         int pageSize, int pageOffset)
        {
            return q.Skip((pageOffset - 1) * pageSize).Take(pageSize);
        }
    }
}

Usage, so instead of...

return View(_productsRepository.Products.OrderBy(x => x.Description)
            .Skip((page - 1) * PageSize).Take(PageSize)
            .ToList());

...which is very brittle, use this instead:

return View(_productsRepository.Products.OrderBy(x => x.Description)
            .LimitAndOffset(pageSize: PageSize, pageOffset: page)
            .ToList());


NUnit Testing:
[Test]
public void Is_paging_logic_correct()
{
 var p = new int[] { 1, 2, 3, 4, 5};

 var e = p.AsQueryable().LimitAndOffset(3, 2).ToArray();

 Assert.AreEqual(2, e.Count());
 Assert.AreEqual(4, e[0]);
 Assert.AreEqual(5, e[1]);
 
}

No comments:

Post a Comment