How do I use Linq for paging a generic collection?

后端 未结 2 1906
太阳男子
太阳男子 2021-02-19 06:20

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 MyCus

相关标签:
2条回答
  • 2021-02-19 06:40

    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.

    0 讨论(0)
  • 2021-02-19 06:55

    Hi There is a wicked thing called PagedList which i got when watching a Rob Conery Screen Cast.

    http://blog.wekeroad.com/2007/12/10/aspnet-mvc-pagedlistt/

    It has all the Skip and Take stuff built in.

    All you do is call

    var query = from item in DB.Table
    where item.Field == 1
    orderby item.Field2
    select item;
    
    PagedList<MyType> pagedList = query.ToPagedList(pageIndex, pageSize);
    

    Hope it helps.. I'm using it now and it works ok for linq to entities. With Linq to entities you have to perform an Orderby before you can use Skip and Take.

    0 讨论(0)
提交回复
热议问题