[英]linq ordering grouped elements after groupby
I have a table that looks like this: 我有一个看起来像这样的表:
| FruitID | BasketID | FruitKind | HarvestTime |
| 23 | 2 | 6 | 1/13/2013 |
| 24 | 2 | 3 | 1/19/2013 |
| 25 | 5 | 4 | 1/21/2013 |
| 26 | 5 | 3 | 1/31/2013 |
| 27 | 5 | 6 | 2/3/2013 |
I want to query all the fruits that are in a certain list of BasketID
, group the result by BasketID
, and within each group, look at the last HarvestTime
and return a list of all the BasketIDs
that contain fruits with the FruitKind
of 3 or 4 (FruitKind can have values between 1 and 8). 我想查询所有那些在某个列表中的水果
BasketID
,组结果由BasketID
,每个组内,看看最后HarvestTime
并返回所有的列表BasketIDs
含有水果与FruitKind
的3或4 (FruitKind的值可以在1到8之间)。 For instance, if we pass in BasketID
2 and 5, BasketID
2 would make it back because its latest FruitID
24 has a FruitKind
of 3 but BasketID
5 has FruitID
27 that's of kind 6. 例如,如果我们传入
BasketID
2和5,则BasketID
2将返回,因为其最新的FruitID
24的FruitKind
为3但BasketID
5的FruitID
27属于种类6。
This is where I'm stuck: 这就是我被困的地方:
var TheQuery = (from a in MyDC.TableFruits
where TheListOfBasketIDs.Contains(a.BasketID)
group a by a.BasketID into g
where .... "latest FruitID has FruitKind == to 3 || 4"
select g.Key).ToList();
I need to ordery HarvestTime within each group so that I can test for the FruitKind of the latest Fruit. 我需要在每个组中对HarvestTime进行排序,以便我可以测试最新Fruit的FruitKind。 Thanks for your suggestions.
谢谢你的建议。
If I understand you correctly, then 如果我理解正确的话,那么
var TheQuery = (from a in MyDC.TableFruits
where TheListOfBasketIDs.Contains(a.BasketID)
group a by a.BasketID into g
let lastFruitKind = g.OrderByDescending(x => x.HarvestTime)
.First().FruitKind
where lastFruitKind == 3 ||
lastFruitKind == 4
select g.Key).ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.