Click here to Skip to main content
15,914,363 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi All

I want to get last two records from a table using LINQ (as we are using TOP 2 for SQL Query).

can anyone help me?

Thanks in advance.
-Amol
Posted

C#
YourTable.OrderBy(t => t.SomeColumn).Take(2)

Is the LINQ equivalent of
SQL
SELECT TOP (2) * FROM YourTable ORDER BY SomeColumn
 
Share this answer
 
Comments
Amol_27101982, India 28-Sep-11 3:28am    
Thanks a lot.
Sometimes, we need to select a record that has the maximum or minimum value from a group. Some examples are:

We have a PersonOrders table and we want to find the last Order for each Person
We have a UserOperations table and we need to find the first Operation for each User
We have a Persons table and we need to find the person with maximum salary for each Department

Such scenarios are beautifully handled by TSQL’s Ranking_functions over partition by clauses. Here’s a typical example that uses Row_Number() function to assign a rank to each row per Person.
SQL
;With PersonOrderWithRank
as
(
    Select *, Rnk = ROW_NUMBER() over (partition by PersonID order by OrderDate desc)
    from PersonOrders
)

Select *
from PersonOrderWithRank
where Rnk=1

In LINQ, similar result can be achieved by using the let keyword. Here’s an example:
SQL
from p in PersonOrders
//where conditions or joins with other tables to be included here
group p by p.PersonID into grp
let MaxOrderDatePerPerson = grp.Max ( g=>g.OrderDate )

from p in grp
where p.OrderDate == MaxOrderDatePerPerson
select p

Another more compact method would be to retrieve the first record in the grouping like this:
SQL
from p in PersonOrders
//where conditions or joins with other tables to be included here
group p by p.PersonID into grp
select grp.OrderByDescending(g=>g.OrderDate).First()

The above LINQ approaches can be used for both LINQ To SQL as well as Entity Framework. Although the SQL and the LINQ approaches I described above are not exactly identical (since I used Row_Number() and not Rank() or Dense_Rank() ) but the purpose of this post is to provide an starting point to write similar queries using LINQ.
 
Share this answer
 
v2
Comments
Amol_27101982, India 28-Sep-11 3:28am    
Thanks a lot.
please try with below software.
it was convert your sql query in to Linq.
http://www.softpedia.com/get/Programming/Other-Programming-Files/Linqer.shtml[^]
 
Share this answer
 
v2
Comments
Amol_27101982, India 28-Sep-11 3:28am    
Thanks a lot.
Amol_27101982, India 28-Sep-11 3:59am    
This tool is simply outstanding…

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900