I have a PredicateBuilder
expression which returns an IQueryable
like so (contrived example):
var predicate = PredicateBuilder.True<CoolEntity>();
predicate = predicate.And(x => x.id > 0);
IQueryable<CoolEntity> results = CoolEntityRepository
.FindBy(predicate)
.OrderByDescending(x => x.id);
I then use this to generate a paginated list containing only the results for a given page using an MVC Index controller for CoolEntity
entities like so:
int total = results.Count(); //Used by my controller to show the total number of results
int pageNumber = 2;
int pagesize = 20;
//Only get the entities we need for page 2, where there are 20 results per page
List<CoolEntity> resultList = results
.Skip(pageNumber * pageSize)
.Take(pageSize)
.ToList()
This query ensures that only the relevant results are returned for each page, as there are many thousands of records returned from an SQL database via the repository. It has been working nicely.
The problem is, I now want to be able to find out which of the paginated pages for my Index I would need to return for a particular entity. For example, say one of my CoolEntity objects has an ID of 5 - how could I determine what the value for pageNumber
would need to be if I wanted to load the paginated page that that entity would be on for my Index controller?
Specifically, how could I find out that for results
, the entity with ID 5 was the 651st row, and consequently use this number to determine pageNumber
(i.e. Math.Ceiling(651/pagesize)
or something similar)? Is there a better approach to this?