2014-10-19 71 views
0

一組的前兩個元素我有一個表,看起來像這樣:查詢由降

FruitID | FruitDate | FruitType 
    23 | 10/20/14 | 3 
    32 | 10/12/14 | 3 
    39 | 09/23/14 | 3 

有許多FruitTypes,我想提取包含最後兩個水果對象模型的列表,例如{FruitID : 23, Date: 10/20}, {FruitID : 32, Date: 10/12}

這是我有:

var Output = (from f in MyDC.Fruits 
       where ... some condition 
       orderby f.FruitDate descending 
       group f by f.FruitType in FruitGroups 
       select.... new FruitModel() 
       { 
        FruitID = ... 
        FruitDate = ... 
        FruitType = ... 

       }).ToList(); 

我無法利用最新2.我怎樣才能找回過去的2的列表每個FruitType

謝謝。

回答

1
var Output = (from f in MyDC.Fruits 
       where ... some condition 
       orderby f.FruitDate descending 
       group f by f.FruitType in FruitGroups 
       select.... new FruitModel() 
       { 
        FruitID = ... 
        FruitDate = ... 
        FruitType = ... 

       }).Take(2).ToList(); 

後續編輯

新增失蹤from條款;這是查詢:

var Output = (from f in MyDC.Fruits 
       where ... some condition 
       orderby f.FruitDate descending 
       group f by f.FruitType in FruitGroups 
       from t in FruitGroups 
       select new FruitModel() 
       { 
        FruitID = t.FruitID, 
        FruitDate = t.FruitDate 
        FruitType = t.FruitType 

       }).Take(2).ToList(); 
+0

好吧,那讓我開始了;仍然需要在select之前添加一個新的from子句。進行編輯。但是,謝謝!這是答案! – frenchie 2014-10-19 23:51:08

+0

Upvoted,你會得到答案複選標記 – frenchie 2014-10-19 23:53:40

+0

如果這回答了你的問題,請將此標記爲答案:)如果除此之外還有其他問題,請不要問 – 2014-10-19 23:55:23

0

試試這個: -

var query = from fruit in fruitsData 
         group fruit by fruit.FruitType into g 
         select new 
         { 
          FruitType = g.Key, 
          Fruits = g.OrderByDescending(x => x.FruitDate).Take(2) 
         }; 

工作Fiddle