限制从Linq返回列表中的结果数 [英] Limit Number of Results being returned in a List from Linq

查看:75
本文介绍了限制从Linq返回列表中的结果数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Linq/EF4.1从数据库中提取一些结果,并希望将结果限制为(X)个最新结果.其中X是用户设置的数字.

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.

有没有办法做到这一点?

Is there a way to do this?

我当前将它们作为List传递回去,如果这将有助于限制结果集.虽然我可以通过循环直到我打X来限制它,但是我只是假设不传递多余的数据.

I'm currently passing them back as a List if 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.

只要有关系... 从SQL Server数据库运行的C#MVC3项目.

Just in case it is relevant... C# MVC3 project running from a SQL Server database.

推荐答案

使用Take函数

int numberOfrecords=10; // read from user
listOfItems.OrderByDescending(x => x.CreatedDate).Take(numberOfrecords)

假设listOfItems是您的实体对象的列表,并且CreatedDate是一个具有创建日期值的字段(用于此处通过降序获取最新商品来进行订购).

Assuming listOfItems is List of your entity objects and CreatedDate is a field which has the date created value (used here to do the Order by descending to get recent items).

Take()函数从a的开头返回指定数量的连续元素 顺序.

Take() Function returns a specified number of contiguous elements from the start of a sequence.

http://msdn.microsoft.com/en-us/library/bb503062.aspx

这篇关于限制从Linq返回列表中的结果数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆