Over a million developers have joined DZone.

Get Last N Records Using Linq-to-SQL

· Database Zone

Build fast, scale big with MongoDB Atlas, a hosted service for the leading NoSQL database. Try it now! Brought to you in partnership with MongoDB.

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

Now it's easier than ever to get started with MongoDB, the database that allows startups and enterprises alike to rapidly build planet-scale apps. Introducing MongoDB Atlas, the official hosted service for the database on AWS. Try it now! Brought to you in partnership with MongoDB.

Topics:

Published at DZone with permission of Pranay Rana, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}