2009-04-16 85 views
2

如果我有這3類:LINQ - 分組和聚集

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

回答

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

爲了獲得最新的招生每門課程的學生已經採取了,我會使用類似:

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

這就是你要求的嗎?