C# 限制从 Linq 的列表中返回的结果数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10883451/
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
Limit Number of Results being returned in a List from Linq
提问by Jared
I'm using Linq/EF4.1 to pull some results from a database and would like to limit the results to the (X) most recent results. Where X is a number set by the user.
我正在使用 Linq/EF4.1 从数据库中提取一些结果,并希望将结果限制为 (X) 最新结果。其中 X 是用户设置的数字。
Is there a way to do this?
有没有办法做到这一点?
I'm currently passing them back as a Listif this will help with limiting the result set. While I can limit this by looping until I hit X I'd just assume not pass the extra data around.
我目前正在将它们传回,List如果这将有助于限制结果集。虽然我可以通过循环来限制这一点,直到我点击 X 我只是假设不会传递额外的数据。
Just in case it is relevant... C# MVC3 project running from a SQL Server database.
以防万一它是相关的...从 SQL Server 数据库运行的 C# MVC3 项目。
采纳答案by Shyju
Use the Takefunction
使用Take功能
int numberOfrecords=10; // read from user
listOfItems.OrderByDescending(x => x.CreatedDate).Take(numberOfrecords)
Assuming listOfItemsis List of your entity objects and CreatedDateis a field which has the date created value (used here to do the Order by descending to get recent items).
假设listOfItems是您的实体对象的列表,并且CreatedDate是一个具有创建日期值的字段(此处用于通过降序进行排序以获取最近的项目)。
Take() Function returns a specified number of contiguous elements from the start of a sequence.
Take() 函数从序列的开头返回指定数量的连续元素。
回答by Mr. TA
results = results.OrderByDescending(x=>x.Date).Take(10);
The OrderByDescending will sort items by your date/time property (or w/e logic you want to use to get most recent) and Take will limit to first x items (first being most recent, thanks to the ordering).
OrderByDescending 将按您的日期/时间属性(或您想要用来获取最新的逻辑)对项目进行排序,而 Take 将限制为前 x 个项目(首先是最近的,感谢排序)。
Edit:To return some rows not starting at the first row, use Skip():
编辑:要返回一些不是从第一行开始的行,请使用Skip():
results = results.OrderByDescending(x=>x.Date).Skip(50).Take(10);
回答by RedFilter
Use Take(), before converting to a List. This way EF can optimize the query it creates and only return the data you need.
Take()在转换为列表之前使用, 。这样 EF 可以优化它创建的查询并且只返回您需要的数据。

