0

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?

Aaron Newton
  • 2,124
  • 1
  • 28
  • 31

1 Answers1

0

A colleague of mine came up with a solution for this which seems to be very fast.

results 
   .Select( x => x.id)
       .ToList()
       .Select((entry, index) => new { ID = entry, Rank = index + 1, PageNumer = ((index+ 1) / pagesize ) + 1 })
       .Where(x => x.id== 5)

This found the result from ~100000 records in about 00:00.191 seconds when tested in Linqpad. Please let me know if you have a more efficient way of doing this.

Aaron Newton
  • 2,124
  • 1
  • 28
  • 31