Click here to Skip to main content
Click here to Skip to main content

Get Last n Records using Linq to SQL

By , 4 Nov 2012
Rate this:
Please Sign up or sign in to vote.

The small post is about getting last n number of record(s) from the database table or from the collection using LINQ.
 

SQL
To get last n number of record(s) from table I do write the following query on my table records in T-SQL.
 

SELECT TOP n <fields> FROM Forms WHERE <field> = <data> 
ORDER BY <field> DESC

As you see in above query important thing is using order by with desc keyword means reversing the table records - (mostly we apply the order by desc on the primary key of the table).
 

LINQ
In LINQ we achieve the same thing with the help of OrderByDescending function and Take function.

var qry = db.ObjectCollection
                     .Where(m => m.<field> == data) 
                     .OrderByDescending(m => m.<field>) 
                     .Take(n); 
In above LINQ query same as sql need to apply the where condition first than make collection reverse using order by function and to get top record you just need to make user of Take function.
 
But to get the last record for the collection you make use of FirstOrDefault function as below
var qry = db.ObjectCollection
                     .Where(m => m.<field> == data) 
                     .OrderByDescending(m => m.<field>) 
                     .FirstOrDefault(); 
 
Read about the method use on MSDN

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Pranay Rana
Software Developer (Senior) GMind Solusion
India India

Microsoft C# MVP (12-13)

 
Hey, I am Pranay Rana, working as a ITA in MNC. Web development in Asp.Net with C# and MS sql server are the experience tools that I have had for the past 5.5 years now.
 
For me def. of programming is : Programming is something that you do once and that get used by multiple for many years
 

You can visit my blog

StackOverFlow - http://stackoverflow.com/users/314488/pranay
My CV :- http://careers.stackoverflow.com/pranayamr
 
Awards:


Follow on   Twitter   LinkedIn

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Mobile
Web03 | 2.8.140415.2 | Last Updated 5 Nov 2012
Article Copyright 2012 by Pranay Rana
Everything else Copyright © CodeProject, 1999-2014
Terms of Use
Layout: fixed | fluid