如果我有这3个班级:

class Student { int id; string name; }
class Course { int id; string name; }
class Enrolment { int studentId; int courseId; DateTime enrolmentDate; }


然后使用这个:

IEnumerable<Course> FindCoursesForStudent(Student student)
{
    return from enrolment in Enrolments
           where enrolment.studentId == student.id
           join course in Courses
              on enrolment.courseId equals course.id
           select course;
}


我可以列出学生注册的所有课程。

但是,如果一个学生报读一门课程不止一次,我如何只显示每门课程的最新报名?

我假设我需要按课程分组并过滤,在哪里enrolmentDate = Max(enrolmentDate)或类似的东西?

(如果这看起来很熟悉,那是因为这是我previous LINQ question的后续内容。)

最佳答案

Enumerable<Course> FindCoursesForStudent(Student student)
{
    return from enrolment in Enrolments
           where enrolment.studentId == student.id
           && enrolment.enrolmentDate == (from ed in Enrolments
           where ed.enrolmentDate == enrolment.enrolmentDate
           select ed.enrolmentDate).Max()
           join course in Courses
              on enrolment.courseId equals course.id
           select course;
}

08-25 23:57