LINQ to SQL: GroupBy() and Max() to get the object with latest date

后端 未结 3 1130
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-28 12:13

Consider a SQL Server table that\'s used to store events for auditing.

The need is to get only that latest entry for each CustID. We want to get the entire

3条回答
  •  醉话见心
    2020-12-28 13:14

    I'm wondering if something like:

    var custsLastAccess = db.CustAccesses   
                        .Where(c.AccessReason.Length>0)
                        .GroupBy(c => c.CustID)
                        .Select(grp => new {
                          grp.Key,
                          LastAccess = grp
                             .OrderByDescending(x => x.AccessDate)
                             .Select(x => x.AccessDate)
                             .FirstOrDefault()
                        }).ToList();
    

    you could also try OrderBy() and Last()

提交回复
热议问题