C# Linq to 实体 Skip() 和 Take()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10950388/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Linq to Entities Skip() and Take()
提问by DotnetSparrow
I am working on an ASP.NET application and I am creating a LINQ query which will select paginated records from db. on user interface I have a listbox where user can select multiple choices. I want to know:
我正在开发一个 ASP.NET 应用程序,我正在创建一个 LINQ 查询,它将从数据库中选择分页记录。在用户界面上,我有一个列表框,用户可以在其中选择多个选项。我想知道:
How can I increment Skip(), Take() parameters to view next results ?
How can I use "IN" key word so that if user selects multiple options from listbox, query can check all values ?
如何增加 Skip()、Take() 参数以查看下一个结果?
如何使用“IN”关键字,以便如果用户从列表框中选择多个选项,查询可以检查所有值?
My query looks like this:
我的查询如下所示:
var searchResults = context.data_vault.Where(d => d.STATE == lstStates.SelectedItem.Text).OrderBy(d= > d.dv_id).Take(10).Skip(2);
GridView1.DataSource = searchResults;
GridView1.DataBind();
回答by abatishchev
You need to turn paging on the GridView first. Then on PageIndexChangingevent:
您需要先在 GridView 上打开分页。然后在PageIndexChanging事件:
var result = db.Where(...)
.Skip(e.NewPageIndex * grid.PageSize)
.Take(grid.PageSize)
.ToList(); // this is very important part too
To emulate INbehavior:
模仿IN行为:
var selection = list.SelectedItems.Select(i => i.Text).ToArray();
var result = db.Where(x => selection.Contains(x.Prop));
回答by Neil N
I think you are using Skip incorrectly. It should be before the Take.
我认为您使用 Skip 不正确。它应该在 Take 之前。
Skip skips a number of records, so for your first page, pass in 0, else pass in the (page number - 1) * records per page.
Skip 会跳过许多记录,因此对于您的第一页,传入 0,否则传入 (page number - 1) * 每页记录。
I usually do something like this:
我通常做这样的事情:
int Page = 1;
int RecordsPerPage = 10;
var q = yourQuery.Skip((Page - 1) * RecordsPerPage).Take(RecordsPerPage);
回答by Kapil Khandelwal
Try this:
尝试这个:
int temp = (CurrentPageNumber - 1) * 10;
var searchResults = context.data_vault.Where(d => d.STATE == lstStates.SelectedItem.Text).OrderBy(d= > d.dv_id).Skip(temp).Take(10);

