Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Paging with LINQ for objects

Tags:

c#

.net

linq

paging

How would you implement paging in a LINQ query? Actually for the time being, I would be satisfied if the sql TOP function could be imitated. However, I am sure that the need for full paging support comes up sooner later anyway.

var queryResult = from o in objects                   where ...                   select new                       {                          A = o.a,                          B = o.b                       }                    ????????? TOP 10???????? 
like image 937
user256890 Avatar asked Mar 04 '10 15:03

user256890


1 Answers

You're looking for the Skip and Take extension methods. Skip moves past the first N elements in the result, returning the remainder; Take returns the first N elements in the result, dropping any remaining elements.

See MSDN for more information on how to use these methods: http://msdn.microsoft.com/en-us/library/bb386988.aspx

Assuming you are already taking into account that the pageNumber should start at 0 (decrease per 1 as suggested in the comments) You could do it like this:

int numberOfObjectsPerPage = 10; var queryResultPage = queryResult   .Skip(numberOfObjectsPerPage * pageNumber)   .Take(numberOfObjectsPerPage); 

Otherwise if pageNumber is 1-based (as suggested by @Alvin)

int numberOfObjectsPerPage = 10; var queryResultPage = queryResult   .Skip(numberOfObjectsPerPage * (pageNumber - 1))   .Take(numberOfObjectsPerPage); 
like image 136
David Pfeffer Avatar answered Sep 21 '22 11:09

David Pfeffer