Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 949
Pankaj Upadhyay Avatar asked Dec 16 '11 10:12

Pankaj Upadhyay


People also ask

How do you get the last row in LINQ?

If you think there is a chance your table may be empty, use LastOrDefault()[^] instead. This will return null if nothing is found. var lastItem = yourQuery. LastOrDefault(); if(lastItem == null) { //Table was empty. }

What is query syntax and method syntax in LINQ?

Query syntax and method syntax are semantically identical, but many people find query syntax simpler and easier to read. Some queries must be expressed as method calls. For example, you must use a method call to express a query that retrieves the number of elements that match a specified condition.

Which of the following clauses can be used to end a LINQ query expression?

LINQ query syntax always ends with a Select or Group clause. The Select clause is used to shape the data.


1 Answers

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.

like image 139
James Avatar answered Oct 04 '22 10:10

James