On my homepage, I want to show the recently added products. I have added a ChildAction to my controller but i am unable to understand what Linq query should i run to fetch the last five records.
Asked
Active
Viewed 6.1k times
31
-
2the last 5 is the **first 5** if you order them the other way around ;o) – balexandre Dec 16 '11 at 10:24
6 Answers
64
LINQ
var lastFiveProducts = (from p in products
orderby p.ProductDate descending
select p).Take(5);
Lambda
var lastFiveProducts = products.OrderByDescending(p => p.ProductDate).Take(5);
Which ever you prefer.

James
- 80,725
- 18
- 167
- 237
-
Which one is optimized more ? means not IEnumerable because it load all data and perform linq on it need IQueryable which takes specific records direct from database .? – Ahmad Nov 01 '19 at 10:28
42
.Skip(count - 5);
or
.Reverse().Take(5).Reverse()

undefined
- 33,537
- 22
- 129
- 198
-
Best solution for me - I didn't have a field to order-by-descending on (as suggested in other answers) – tarrball Sep 07 '15 at 17:39
-
-
@user, In the first case not strictly but its probably good habit if you have any concurrency going on. – undefined Feb 23 '17 at 04:04
16
The simplest approach is to reverse your ordering (e.g. use orderby foo descending
) and then use Take()
. For example:
var recentProducts = products.OrderByDescending(x => x.CreationDate)
.Take(5);
or in query expression form (which I wouldn't use for simple queries which are more easily expressed in the above form):
var recentProducts = (from product in products
orderby product.CreationDate descending
select product).Take(5);

Jon Skeet
- 1,421,763
- 867
- 9,128
- 9,194
-
hmm.....one other good thing came out of this....i didnt had a creationDate column in my table. Will add that too – Pankaj Upadhyay Dec 16 '11 at 10:30
-
1@PankajUpadhyay Everyone (as you can see) assumed you had a date as you mentioned *recent products*. However, you could also do it via the product ID (given it's ordered in some way e.g. auto-increment) although I would recommend a created date of some sort. – James Dec 16 '11 at 10:32
-
@James , ya that what i really loved to learn. Adding a creation date will help in lot of things later on which i was missing. Thank you guys for the rescue. I asked for one and got two in return :) – Pankaj Upadhyay Dec 16 '11 at 10:39
1
This is for selecting the last 5 with ascending
var query = from tbl in (from tbl1 in object.Table orderby
tbl1.Column descending select tbl1).Take(5) orderby tbl.Column
ascending select tbl;

Stef Geysels
- 1,023
- 11
- 27

Jai
- 269
- 2
- 4
0
Code:
INT[]number = new int[] {3,6,8,2,3,7,0,2,5}
var result= (from r in number select r).reverse().take(5);
result: 5 2 0 7 3

tostao
- 2,803
- 4
- 38
- 61