Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the total number of records when doing pagination

To get a page from a database I have to execute something like this:

var cs = ( from x in base.EntityDataContext.Corporates
   select x ).Skip( 10 ).Take( 10 );

This will skip the first 10 rows and will select the next 10.

How can I know how many rows would result because of the query without pagination? I do not want to run another query to get the count.

like image 455
effkay Avatar asked Jan 05 '10 19:01

effkay


2 Answers

To get the total number of records before skip/take you have to run a separate query. Getting the actual number returned would use Count(), but wouldn't result in another query if the original query was materialized.

var q = from x in base.EntityDataContext.Corporates 
        select x;

var total = q.Count();
var cs = q.Skip(10).Take(10);
var numberOnSelectedPage = cs.Count();
like image 111
tvanfosson Avatar answered Sep 29 '22 11:09

tvanfosson


Bottom line: you have to run two queries. You simply can't get around it.

Here's a good way to do it, however, that caches the original LINQ query and filter, making for less copy/paste errors:

var qry = from x in base.EntityDataContext.Coporates select x;
var count = qry.Count();
var items = qry.Skip(10).Take(10).ToList();
like image 21
Randolpho Avatar answered Sep 29 '22 11:09

Randolpho