asp.net-mvclinqpagination

how can i page into my list using linq


i have a linq query to get data from a database. something like:

Repository.Query<Project>.Where(r=>r.IsActive).OrderBy(r=>r.Date);

i then return this to a viewmodel. i now want to add paging so i get an additional parameter in my controller action which is the page so i want something to add to my query to return lets say 10 results * the page number:

So if its page 1, i want to get the first 10 results. I know i can use the

.Take(10)

to do this but i am unsure how to do this when the page passed in is 2 or 3 or anything but 1.

what is the best way (and most efficient) to do this ??


Solution

  • Use a combination of Skip and Take:

    .Skip((page - 1) * resultsPerPage).Take(resultsPerPage);