开发者

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 ??


Use a combination of Skip and Take:

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


Make an extension method. Chances are, you'll need this all over your web application.

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);
}

Usage:

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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜