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

后端 未结 3 1108
爱一瞬间的悲伤
爱一瞬间的悲伤 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:11

    Here: this uses max rather than OrderByDesc, so should be more efficient.

    var subquery = from c in CustAccesses
                group c by c.CustID into g
                select new
                {
                    CustID = g.Key,
                    AccessDate = g.Max(a => a.AccessDate)
                };
    var query = from c in CustAccesses
                join s in subquery 
                  on c.CustID equals s.CustID
                where c.AccessDate == s.AccessDate
                 && !string.IsNullOrEmpty(c.AccessReason)
                select c;
    
    0 讨论(0)
  • 2020-12-28 13:13

    Using LINQ syntax, which I think looks cleaner:

    var custsLastAccess = from c in db.CustAccesses 
                          group c by c.CustID into grp
                          select grp.OrderByDescending(c => c.AccessDate).FirstOrDefault();
    
    0 讨论(0)
  • 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()

    0 讨论(0)
提交回复
热议问题