如果我有这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的后续内容。)
答案 0 :(得分:2)
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;
}
答案 1 :(得分:1)
要获得学生每门课程的最新报名,我会使用以下内容:
IEnumerable<Enrolment> FindCoursesForStudent(Student student) {
return from enrolment in Enrolments
where enrolment.studentId == student.id
group enrolment by enrolment.courseId into gp
select gp.OrderBy(e => e.enrolmentDate).First();
}
这就是你要求的吗?