我对LINQ很新。
假设我有下表:
Incident
ID DeviceID Time Info
1 1 5/2/2009 d
2 2 5/3/2009 c
3 2 5/4/2009 b
4 1 5/5/2009 a
在LINQ中,如何编写查找最新且不同(在设备ID上)事件集的查询?我想要的结果就是:
ID DeviceID Time Info
3 2 5/4/2009 b
4 1 5/5/2009 a
您是否必须创建IEqualityComparer才能执行此操作?
答案 0 :(得分:16)
您可以通过以下方式获取每个设备的最新事件(这是我理解您的问题的方式):
var query =
incidents.GroupBy(incident => incident.DeviceID)
.Select(g => g.OrderByDescending(incident => incident.Time).First())
.OrderBy(i => i.Time); // only add if you need results sorted
答案 1 :(得分:4)
int filterDeviceID = 10;
var incidents = (from incident in incidentlist
where incident.DeviceID == filterDeviceID
select incident).Distinct().OrderBy( x => x.Time);