tags:

views:

524

answers:

4

Hi, 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?

A: 

This avoids counting the number of rows:

var query = from p in db.ProductList select p;

int page = 0;
while(true) {
    var currentPage = query.Skip(page * row_per_page).Take(row_per_page);
    if(!currentPage.Any()) {
        break;
    }
    // use current page
    page++;
}
Jason
does this not execute 2 queries?
Myster
A: 

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

var count = (from l in db.ProductList select l).Count();
JaredPar
or: var count = db.ProductList.Count()
Mel Gerats