Get top 5 values with lambda query

53,782

Solution 1

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.

Solution 2

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

Solution 3

Just use Take(n) in LINQ

rptAnnouncement.DataSource = DbContext.Announcements
                                      .Where(n => n.Expire_Date.Value.Date >= DateTime.Now.Date)
                                      .Take(5).ToList();
Share:
53,782
zey
Author by

zey

Updated on May 11, 2020

Comments

  • zey
    zey about 4 years

    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.

  • zey
    zey about 11 years
    Thanks , i do forget to order by date :D
  • zey
    zey about 11 years
    ha ha :D . by the way Daniel , how can i set (ascending , descending ) to order !
  • It'sNotALie.
    It'sNotALie. about 11 years
    It should be .Take(5).ToList(), not the opposite.