简体   繁体   中英

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). 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.

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. 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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM