Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ - writing a query with distinct and orderby

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?

like image 605
David Hodgson Avatar asked Aug 05 '09 20:08

David Hodgson


2 Answers

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
like image 141
mmx Avatar answered Oct 20 '22 07:10

mmx


int filterDeviceID = 10;

var incidents = (from incident in incidentlist
                where incident.DeviceID == filterDeviceID
                select incident).Distinct().OrderBy( x => x.Time);
like image 40
womp Avatar answered Oct 20 '22 07:10

womp