How to retrieve last 5 records using LINQ method or query expression in C#

Pankaj Upadhyay picture Pankaj Upadhyay · Dec 16, 2011 · Viewed 50.6k times · Source

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.

Answer

James picture James · Dec 16, 2011

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.