views:

374

answers:

3

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 object/row. I am assuming that a GroupBy() will be needed in the query. Here's the query so far:

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

Question: How can I create the query to select the latest(the maximum AccessDate) record/object for each CustID?

+2  A: 

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).First()
                    }).ToList();

?? (completely untested; you could also try OrderBy() and Last())

Marc Gravell
A: 
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();
vladhorby
A: 

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