Choose n largest using LINQ

This is most likely new to the LINQ question, but provided that I have a set of elements with the DateTime property, with one date having at most one element, how can I select the N most recent elements from the link date, i.e. N elements whose date is less than the requested date and the largest date?
My naive thought would be to first select the elements with a date less than the key date, sort by date and select the N first elements from this subset.

 var recentItems = from item in dataContext.Items
              where item.Date<=date 
              orderby item.Date descending 
              select item;

 var mostRecentItems = recentItems.Take(5).ToList();

Is this the “right” way to do this, or are there obviously better ways to achieve my goal?

+3
source share
3 answers

, . dataContext, , Linq to SQL; TOP N .

(, "", .)

, , - ToList(). , IEnumerable<T>, , .

: , , ToList. ToList, , . , . , , , .

5 , , ; 5000 . ToList(), , . .

+5

, , .

+3

, . 1 :

 var recentItems = (from item in dataContext.Items
              where item.Date<=date 
              orderby item.Date descending 
              select item).Take(5).ToList();

.

+2

Source: https://habr.com/ru/post/1744858/


All Articles