2009-08-05 6 views
12

私はLINQを新しく導入しました。どのように私は、事件の最新のと(デバイスIDの)明確なセットを見つけるクエリを書くことができ、LINQではLINQ - distinctとorderbyを使用してクエリを書く

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 

は、私は、次の表を持っていたと仮定しますか?私が望む結果は次のとおりです。

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

うん、私が行っていたまさに。ありがとう。 –

4
int filterDeviceID = 10; 

var incidents = (from incident in incidentlist 
       where incident.DeviceID == filterDeviceID 
       select incident).Distinct().OrderBy(x => x.Time); 
関連する問題