How can I make a page in my list using linq

I have a linq query to retrieve data from a database. sort of:

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

i then return it to view mode. Now I want to add a paging, so I get an additional parameter in my controller action, which is a page, so I want to add something to my query in order to return, say, 10 results * page number:

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

.Take(10)

but I'm not sure how to do this when the page went through 2 or 3 or something other than 1.

What is the best way (and most effective) for this?

+3
source share
3 answers

Use a combination of Skipand Take:

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

. , -.

public static IEnumerable<T> TakePage<T>(this IEnumerable<T> items, int page, int pageSize = 10) where T : class
{
    return items.Skip(pageSize * (page - 1)).Take(pageSize);
}

:

int page = 2;
int pageSize = 25;
Repository.Query<Project>.Where(r=>r.IsActive).TakePage(page, pageSize);
0

: .Skip((page ?? 0) * resultsPerPage).Take(resultsPerPage);

0

Source: https://habr.com/ru/post/1788880/


All Articles