How do I use Linq for paging a generic collection?

时光毁灭记忆、已成空白 提交于 2019-12-21 07:09:00

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/21184/how-do-i-use-linq-for-paging-a-generic-collection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!