LINQ to SQL:GroupBy()和Max()获取具有最新日期的对象

时间:2009-11-10 00:09:53

标签: c# linq linq-to-sql group-by

考虑一个用于存储审核事件的SQL Server表。

需要为每个CustID仅获取最新条目。我们想要获得整个对象/行。我假设在查询中需要GroupBy()。这是迄今为止的查询:

var custsLastAccess = db.CustAccesses   
                        .Where(c.AccessReason.Length>0)
                        .GroupBy(c => c.CustID)
//                      .Select()
                        .ToList();
// (?) where to put the c.Max(cu=>cu.AccessDate) 

Custs Layout

问题: 如何创建查询以选择每个AccessDate的最新(CustID}个最大记录/对象?

4 个答案:

答案 0 :(得分:33)

我想知道是否有:

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();

您还可以尝试OrderBy()Last()

答案 1 :(得分:21)

使用LINQ语法,我觉得它看起来更干净:

var custsLastAccess = from c in db.CustAccesses 
                      group c by c.CustID into grp
                      select grp.OrderByDescending(c => c.AccessDate).FirstOrDefault();

答案 2 :(得分:4)

这里:这使用max而不是OrderByDesc,所以应该更有效率。

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;

答案 3 :(得分:0)

var custsLastAccess = db.CustAccesses   
                            .Where(c.AccessReason.Length>0)
                        .GroupBy(c => c.CustID, (id, custs) => new { ID=id, LastAccess=custs.OrderByDescending(c=>c.AccessDate).First().AccessDate})
                      .Select()
                        .ToList();