c# - 分组列表并在订购后选择所需的项目
问题描述
我有一个大约 100 行的 Course 类型列表。课程有 3 列:代码、描述和年份。所以列表目前看起来像:
Code Description Year
A200 DataB 2018
A200 DataB 2019
A300 DataC 2018
A400 DataD 2019
A500 DataA 2018
A500 DataA 2019
我希望能够返回每年的最新行,然后按描述按字母顺序排列结果。所以最终的结果应该是
A500 DataA 2019 (Latest A500 row and ordered by Description)
A200 DataB 2019 (Latest A200 row)
A300 DataC 2018
A400 DataD 2019
我尝试了以下变体:
List<Course> NewAllCourses = AllCourses
.GroupBy(x => x.CourseCode)
.Select(g => g.Last().CourseYear)
.OrderBy(y => y.CourseDescription)
.ToList();
但我似乎无法让语法正确,并且我尝试的每个版本都出现不同的错误。任何帮助将不胜感激,因为我已经尝试了几个小时,因为我不完全理解我在做什么。
解决方案
您的代码几乎就在那里,唯一的问题是您的 Select() 调用仅选择 CourseYear 值,您想在其中选择整个对象,以便继续处理它。
有点像这样的东西应该起作用:
List<Course> NewAllCourses = AllCourses
.GroupBy(x => x.CourseCode)
//Select the last item from the group, ordered by year.
.Select(g => g.OrderBy(x => x.CourseYear).Last())
.OrderBy(y => y.CourseDescription)
.ToList();
推荐阅读
- javascript - 此函数的 Max.math - 作业
- javascript - 函数在 react.js 中返回“未定义”
- javascript - 如何使用 Cef4Delphi 从 JavaScript 调用 Delphi 函数
- bash - Bash 脚本错误“awk 致命无法打开文件进行读取(没有这样的文件或目录)”
- python - 使用列表理解填充熊猫值字典
- swift - 与标题内联的尾随导航栏项目
- html - 资源未加载到网页上
- swiftui - 带有 Siri Intent 的 SwiftUI 小部件,用于动态选项列表
- python - 如何使用 sklearn 计算具有二进制相关性的 NDCG?
- mysql - 哪个制作公司制作的热门电影数量最多(平均评分> 8)?