LINQ - writing a query with distinct and orderby

时光总嘲笑我的痴心妄想 提交于 2019-12-10 02:06:32

问题


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?


回答1:


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



回答2:


int filterDeviceID = 10;

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


来源:https://stackoverflow.com/questions/1235604/linq-writing-a-query-with-distinct-and-orderby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!