I am trying to select top 5 rows and ordered-descending by Id coloumn without getting all rows into memory. My code is like below...
IList<Article> articles = _articleRepository.GetList(d => d.CategoryId == cat.Id).OrderByDescending(d=>d.Id).ToList();
You need access to an
IQueryable and perform the following LINQ:
dbContext.OrderByDescending(d => d.Id).Take(5).ToList();
This will convert the LINQ expressions into SQL and only fetch the relevant rows from the database. The
ToList() will execute the query and load the five elements into memory.