LINQ SQL分组取最近一条记录
最近项目有一个需求,从订单表查询出每个客户最近一条订单记录。数据库表结构如下图
SELECT * FROM ( select ROW_NUMBER()over(partition by [custid] order by [orderdate] desc) AS newIndex,* from Sales.Orders ) as T where T.newIndex=1
执行结果,已经按照客户分组,并且按时间顺序生成序号。
对应LINQ代码为
var table = contex.GetTable<Orders>().ToList(); var data = table.OrderByDescending(a => a.orderdate).GroupBy(a => a.custid) .Select(g => new { g, count = g.Count() }) .SelectMany(t => t.g.Select(b => b) .Zip(Enumerable.Range(1, t.count), (j, i) => new { j.custid, j.shipname, rn = i }));