Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get top 5 values with lambda query

Tags:

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).

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.

like image 585
zey Avatar asked Mar 30 '13 07:03

zey


People also ask

Which is faster Linq or Lambda?

There is no performance difference between LINQ queries and Lambda expressions.


2 Answers

You can use OrderBy() to order the elements and then Take() to take the first 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 calling Take() will get all of the items and then take the top 5 as opposed to only getting the top 5.
like image 197
Daniel Imms Avatar answered Sep 19 '22 18:09

Daniel Imms


If you only want the Top 5 then you can use the below .

rptAnnouncement.DataSource = DbContext.Announcements.Where(n => n.Expire_Date.Value.Date >= DateTime.Now.Date).Take(5).ToList(); 

More details here

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

like image 36
ashutosh raina Avatar answered Sep 21 '22 18:09

ashutosh raina