C# 使用 lambda 查询获取前 5 个值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15716316/
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
Get top 5 values with lambda query
提问by zey
Here is my code,
这是我的代码,
rptAnnouncement.DataSource = DbContext.Announcements
.Where(n => n.Expire_Date.Value.Date >= DateTime.Now.Date)
.ToList();
I take the announcements data from database with lambda and bind this data to ASP.NET repeater(rptAnnouncement
).
我使用 lambda 从数据库中获取公告数据并将这些数据绑定到 ASP.NET repeater( rptAnnouncement
)。
But this query returns all of the data, I just want to get the top 5 (first 5) records like MS SQL Server's select top 5 * from database
.
但是此查询返回所有数据,我只想获取前 5 条(前 5 条)记录,例如 MS SQL Server 的select top 5 * from database
.
采纳答案by Daniel Imms
You can use OrderBy()
to order the elements and then Take()
to take the first 5.
您可以使用OrderBy()
对元素进行排序,然后Take()
使用前 5 个。
rptAnnouncement.DataSource = DbContext.Announcements
.Where(n => n.Expire_Date.Value.Date >= DateTime.Now.Date)
.OrderBy(n => n.Expire_Date.Value.Date)
.Take(5);
Notes
笔记
- You can order descending by using
OrderByDescending()
- Calling
ToList()
and then callingTake()
will get all of the items and then take the top 5 as opposed to only getting the top 5.
- 您可以使用降序排序
OrderByDescending()
- 调用
ToList()
然后调用Take()
将获取所有项目,然后获取前 5 项,而不是仅获取前 5 项。
回答by ashutosh raina
If you only want the Top 5 then you can use the below .
如果您只想要前 5 名,则可以使用以下 .
rptAnnouncement.DataSource = DbContext.Announcements.Where(n => n.Expire_Date.Value.Date >= DateTime.Now.Date).Take(5).ToList();
More details here
更多细节在这里
回答by Praveen Nambiar
Just use Take(n)
in LINQ
只需Take(n)
在LINQ
rptAnnouncement.DataSource = DbContext.Announcements
.Where(n => n.Expire_Date.Value.Date >= DateTime.Now.Date)
.Take(5).ToList();