首页 > 解决方案 > 分组列表并在订购后选择所需的项目

问题描述

我有一个大约 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();

但我似乎无法让语法正确,并且我尝试的每个版本都出现不同的错误。任何帮助将不胜感激,因为我已经尝试了几个小时,因为我不完全理解我在做什么。

标签: c#linq

解决方案


您的代码几乎就在那里,唯一的问题是您的 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();

推荐阅读