views:

768

answers:

2

Hi, 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?

+4  A: 

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
Mehrdad Afshari
Yep, exactly what I was going for. Thanks.
David Hodgson
+1  A: 
int filterDeviceID = 10;

var incidents = (from incident in incidentlist
                where incident.DeviceID == filterDeviceID
                select incident).Distinct().OrderBy( x => x.Time);
womp