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

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

提交回复
热议问题