LINQ:按聚合分组,但仍然从最近一行获取信息?

时间:2011-10-04 05:52:00

标签: c# linq

假设我有一张包含运送历史记录的表格。我想编写一个查询来计算每个用户的发货量,并从该表中该用户的最新条目中获取发货名称。

表结构简单: ShipmentID 会员ID ShippingName ShippingDate

如何编写LINQ C#查询来执行此操作?

2 个答案:

答案 0 :(得分:5)

听起来可能想要这样的东西:

var query = from shipment in context.ShippingHistory
            group shipment by shipment.MemberID into g
            select new { Count = g.Count(),
                     MemberID = g.Key,
                     MostRecentName = g.OrderByDescending(x => x.ShipmentDate)
                                       .First()
                                       .ShipmentName };

答案 1 :(得分:0)

不是真正的LINQ答案,但个人,我会为此而放弃SQL,以确保它没有做任何N + 1等;例如:

select s1.MemberID, COUNT(1) as [Count],
    (select top 1 ShippingName from Shipping s2 where s2.MemberID = s1.MemberID
     order by s2.ShippingDate desc) as [LastShippingName]
from Shipping s1
group by s1.MemberID

你可能会做类似(未经测试)的LINQ:

var qry = from row in data
          group row by row.MemberId into grp
          select new {
               MemberId = grp.Key,
               Count = grp.Count(),
               LastShippingName =
              grp.OrderByDescending(x => x.ShippingDate).First().ShippingName
           };