C# 按降序查询组的前两个元素
我有一张这样的桌子:C# 按降序查询组的前两个元素,c#,linq,linq-to-sql,C#,Linq,Linq To Sql,我有一张这样的桌子: FruitID | FruitDate | FruitType 23 | 10/20/14 | 3 32 | 10/12/14 | 3 39 | 09/23/14 | 3 有许多水果类型,我想提取一个包含最后两个水果的对象模型列表,例如{groutid:23,Date:10/20},{groutid:32,Date:10/12} 这就是我所拥有的: var Output = (from f in MyDC.Fruits
FruitID | FruitDate | FruitType
23 | 10/20/14 | 3
32 | 10/12/14 | 3
39 | 09/23/14 | 3
有许多水果类型
,我想提取一个包含最后两个水果的对象模型列表,例如{groutid:23,Date:10/20},{groutid: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。如何获取每个水果类型的最后两个的列表
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();
后续编辑
在
子句中添加缺少的;以下是查询:
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();
试试这个:-
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)
};
工作。好的,这让我开始了;仍然需要在select之前添加一个新from子句。做了编辑。但是谢谢!!这就是答案!如果回答了您的问题,请将此标记为答案:)如果您有任何其他问题,请询问