views:

1425

answers:

3

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  A: 

I believe that you have the Take and Skip function to do this.

Jedi Master Spooky
+10  A: 

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.

Espo
+2  A: 

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.

CraftyFella