.NET Zone is brought to you in partnership with:

I am Microsoft C# MVP July - 2012 My name is Pranay Rana. Currently, I'm working as senior software engineer in a mid-sized company (Ahmedabad). I have 5 years of the experience in web development with Asp.Net, C# and MS SQL server. For me, the definition of programming is: something that you do once and that gets used by multiple users for many years Pranay is a DZone MVB and is not an employee of DZone and has posted 34 posts at DZone. You can read more from them at their website. View Full User Profile

Get Last N Records Using Linq-to-SQL

05.27.2012
| 6833 views |
  • submit to reddit
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
Published at DZone with permission of Pranay Rana, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)