I'm quite new to LINQ.
Suppose that I had the following table:
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
In LINQ, how could I write a query that finds the most recent and distinct (on Device ID) set of incidents? The result I'd like is this:
ID DeviceID Time Info
3 2 5/4/2009 b
4 1 5/5/2009 a
Do you have to create an IEqualityComparer to do this?
You can get the most recent incidents for each device (this is how I understood your question) with:
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
int filterDeviceID = 10;
var incidents = (from incident in incidentlist
where incident.DeviceID == filterDeviceID
select incident).Distinct().OrderBy( x => x.Time);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With