2016-07-06 14 views
0

LINQクエリの外部でこれを行うことができますが、私はそれが可能かどうかは疑問でした。LINQグループby並べ替え

私はそれに関連付けられた別個のIDを持つ最新のアイテムを取得しているクエリを送信したいと思います。

は、私は次のオブジェクトがあるとしましょう:

{ 
    ItemDescription: 'Object 1', 
    ItemDate: 1/1/2016, 
    ItemTypeId: 1 
}, 
{ 
    ItemDescription: 'Object 2', 
    ItemDate: 1/1/2016, 
    ItemTypeId: 2 
}, 
{ 
    ItemDescription: 'Object 3', 
    ItemDate: 3/1/2016, 
    ItemTypeId: 1 
}, 

3はItemTypeId=1のより新しいバージョンだったので、私は(オブジェクト2と3を返すために、クエリを希望

それは(私が思う)する必要があります。以下のようなものになる:

var recentItems = (from s in db 
        orderby s.ItemDate descending 
        group s by s.ItemTypeId into uniqueItems 
        select uniqueItems.FirstOrDefault()).ToList(); 

しかし、FirstOrDefaultは順序を上書きします

どのような考えですか?

答えて

2

これは動作するはずです:

var recentItems = (from s in db 
        group s by s.ItemTypeId into uniqueItems 
        select uniqueItems.OrderByDescending(x=> x.ItemDate).FirstOrDefault()) 
                     .ToList(); 
+0

ああ少年は、私がこの場所を愛しています。完璧!ありがとうございました! – twsmale

関連する問題