如何使用LINQ获取最后2条记录 [英] How to get last 2 records using LINQ
问题描述
大家好
我想使用LINQ从表中获取最后两个记录(因为我们在SQL查询中使用TOP 2).
有人可以帮我吗?
提前谢谢.
-Amol
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
推荐答案
YourTable.OrderBy(t => t.SomeColumn).Take(2)
LINQ是否等效于
Is the LINQ equivalent of
SELECT TOP (2) * FROM YourTable ORDER BY SomeColumn
请尝试使用以下软件.
原来是将您的sql查询转换为Linq.
http://www.softpedia.com/get/Programming/Other-Programming-Files/Linqer.shtml [ ^ ]
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[^]
有时,我们需要从组中选择一个具有最大值或最小值的记录.以下是一些示例:
我们有一个PersonOrders表,我们想找到每个Person的最后一个Order
我们有一个UserOperations表,我们需要找到每个用户的第一个操作
我们有一个Persons表,我们需要找到每个部门的最高薪资人员
TSQL的Rank_functions通过partition by子句很好地处理了这种情况.这是一个典型的示例,该示例使用Row_Number()函数为每个人的每一行分配一个等级.
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.
;With PersonOrderWithRank
as
(
Select *, Rnk = ROW_NUMBER() over (partition by PersonID order by OrderDate desc)
from PersonOrders
)
Select *
from PersonOrderWithRank
where Rnk=1
在LINQ中,通过使用let关键字可以实现类似的结果.这是一个示例:
从中的
In LINQ, similar result can be achieved by using the let keyword. Here’s an example:
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:
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()
上面的LINQ方法可用于LINQ To SQL以及实体框架.尽管我上面描述的SQL和LINQ方法并不完全相同(因为我使用Row_Number()而不是Rank()或Dense_Rank()),但是本文的目的是提供一个起点,以便使用LINQ编写类似的查询.
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.
这篇关于如何使用LINQ获取最后2条记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!