开发者

LINQ: Group by aggregate but still get information from the most recent row?

Let's say I have a table that holds shipping history. I'd like to write a query that count开发者_如何学Pythons the amount of shipments per user and gets the shipping name from the most recent entry in the table for that user.

Table structure for simplicity: ShipmentID MemberID ShippingName ShippingDate

How do I write a LINQ C# query to do this?


It sounds like might want something like:

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 };


Not really a LINQ answer, but personally, I'd be dropping to SQL for that, to make sure it isn't doing any N+1 etc; for example:

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

You can probably do LINQ something like (untested):

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
           };
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜