2009-08-05 53 views
12

我對LINQ很陌生。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做到這一點?

回答

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 
+0

沒錯,正是我所要的。謝謝。 – 2009-08-05 20:57:55

4
int filterDeviceID = 10; 

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