Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

linq paging - get total rows

Tags:

i have a question about linq. I'm using Skip and Take to do paging:

(from l in db.ProductList
          select l).Skip((page - 1) * row_per_page).Take(row_per_page)

It work, and i need retrieve total rows of product list to calculate max page. I think i must use another query to count rows but have another way to do this in one query above?

like image 805
complez Avatar asked Nov 14 '09 03:11

complez


2 Answers

To get a count of the rows, use the .Count() extension method

var count = (from l in db.ProductList select l).Count();
like image 146
JaredPar Avatar answered Oct 11 '22 17:10

JaredPar


The bottom line is you will have to enumerate all items to get the total page number. But you would like to enumerate them only once. I suggest you try GroupBy method to get a IEnumerable> "pages". Then you can use pages.Count() to get page count. Or you can enumerate pages to get each page of items. The GroupBy query will be only executed once.

like image 33
treehouse Avatar answered Oct 11 '22 17:10

treehouse