c# - linq在groupby之后排序分组元素

标签 c# linq linq-to-sql

我有一个看起来像这样的表:

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

我想查询 BasketID 的特定列表中的所有水果,按 BasketID 对结果进行分组,并在每个组中查看最后一个 HarvestTime 并返回包含 FruitKind 为 3 或 4 的水果的所有 BasketIDs 的列表(FruitKind 的值可以介于 1 和 8 之间)。例如,如果我们传入 BasketID 2 和 5,BasketID 2 会返回,因为它最新的 FruitID 24 有一个 FruitKind 3,但 BasketID 5 有 FruitID 27,属于 6。

这是我卡住的地方:

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

我需要在每个组内对 HarvestTime 进行排序,以便我可以测试最新 Fruit 的 FruitKind。感谢您的建议。

最佳答案

如果我没理解错的话

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

关于c# - linq在groupby之后排序分组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14705406/

相关文章:

c# - 如何在没有主键的情况下删除重复项(不同值)

c# - 重用 LINQ 查询

c# - NEST Elasticsearch高级排序

c# - 在带有 continue 的循环中使用

c# - 这项工作的最佳抽象类型?

c# - 非重复计数 x 和按日期 y 分组

visual-studio-2008 - 如何将 DBML 图从 Visual Studio 导出到图像中?

C# Linq-to-SQL 创建通用存储库

linq-to-sql - StructureMap DBServiceRegistry 和 MVC-mini-profiler?

c# - Azure Blob 存储 : Mocking CloudBlobContainer