views:

251

answers:

3

I have a simple Linq to Enities table to query and get the most recent records using Date field

So I tried this code:

IQueryable<Alert> alerts = GetAlerts();
IQueryable<Alert> latestAlerts =
    from a in alerts
    group a by a.UpdateDateTime into g
    select g.OrderBy(a => a.Identifier).First();

Error: NotSupportedException: The method 'GroupBy' is not supported.

Is there any other way to get do it? Thanks a lot!

+1  A: 

If there isn't a reason to group it, you could just switch your query up a little:

IQueryable<Alert> alerts = GetAlerts();
IQueryable latestAlerts = alerts.OrderByDescending(a => a.UpdateDateTime);
Benny
This will load the entire database into memory when queried...
BlueRaja - Danny Pflughoeft
@BlueRaja - actually it won't do anything. Until you do something with latestAlerts like .First() or .Take(10) no database hit will occur.
Hightechrider
@hightechrider: Hence the "when queried"... Presumably, the poster was looking for a complete answer.
BlueRaja - Danny Pflughoeft
A: 

It should be

IQueryable<Alert> latestAlerts =
    (from a in alerts
    group a by a.UpdateDateTime into g
    order by g.Key
    select g).First();

GroupBy is definitely supported by Linq-to-Entities

BlueRaja - Danny Pflughoeft
it's not working, the "order by g.key" is "red" -> "a query body must end with select clause or a group clause
Begemotya
Any way I need to group by 2 fields "UpdateDateTime" and "Id" in order to get the most recent record for each id
Begemotya
A: 

So the answer is:

var query =
    from alert in m_alerts
    group alert by alert.Identifier
          into g 
          select new 
          {
        GroupIdentifier = g.Key,
        UpdateDateTime = g.Max(p => p.UpdateDateTime) 
          };

This will return the most recent records.

Begemotya
This will return a new object {Key, Date}Is there a way to return same "alert" objects?
Begemotya