I have the following object
public partial class Log
{
public System.Guid Id { get; set; }
public double Lat { get; set; }
public double Lng { get; set; }
public System.DateTime TimeStamp { get; set; }
public int DeviceId { get; set; }
}
And I would like to get most recent log per device. So I have this
from log in allLogs
group log by log.DeviceId
into l
select new {DeviceId = l.Key, TimeStamp = l.Max(s => s.TimeStamp)};
This works great except that it only includes the deviceId and the TimeStamp. I would also like to include the Lat and Lng fields from the Log as well.
But note these fields are not part of the key or the aggregate function. I.E I don’t want to group by these fields I just want then to be in the result set. So that I have the lat Lng of the most recent log per device.
This would work in LINQ to Objects – I don’t know about LINQ to SQL etc:
In other words, sort each group, and take the latest.
Alternatively, definitely only in LINQ to Objects, you could use
MaxByfrom MoreLINQ: