blog.mha.dk
The on-line blog of Michael Holm Andersen

LINQ and PagedList

Tuesday, 26 January 2010 18:04 by mha

If you’re using LINQ you probably know about the .Skip and .Take methods. However often you need to do paging, hence you probably use something similar to this to get around that:

public PaginatedList(IQueryable<T> source, int pageIndex, int pageSize)
    {
        PageIndex = pageIndex;
        PageSize = pageSize;
        TotalCount = source.Count();
        TotalPages = (int)Math.Ceiling(TotalCount / (double)PageSize);

        this.AddRange(source.Skip(PageIndex * PageSize).Take(PageSize));
    }


However you don’t need the above code – instead take a look at the CodePlex project called PagedList located at http://pagedlist.codeplex.com/

PagedList allows you to take any List<T> and by specifying the page size and desired page index, select only a subset of that list, there’s also a StaticPagedList if you should need that.

Simply download the source, run “Release.bat” to build a release version and reference the .dll file in your solution, then you can have code like this:

var somePage = list.ToPagedList(4, 50); // fifth page, page size = 50

Comments are closed