Search code examples
.netlinqpagination.net-3.5

How do I use Linq for paging a generic collection?


I've got a System.Generic.Collections.List(Of MyCustomClass) type object.

Given integer varaibles pagesize and pagenumber, how can I query only any single page of MyCustomClass objects?


Solution

  • If you have your linq-query that contains all the rows you want to display, this code can be used:

    var pageNum = 3;
    var pageSize = 20;
    query = query.Skip((pageNum - 1) * pageSize).Take(pageSize);
    

    You can also make an extension method on the object to be able to write

    query.Page(2,50)
    

    to get the first 50 records of page 2. If that is want you want, the information is on the solid code blog.