tags:

views:

133

answers:

2

If I have these 3 classes:

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

Then using this:

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

I can list all the Courses a Student is enrolled on.

But if a student has enrolled for a course more than once, how would I only show the most recent enrolment for each course?

I'm assuming I need to group by Course and filter where enrolmentDate = Max(enrolmentDate) or something similar?

(If this looks familiar, it's because it's a follow-on from my previous LINQ question.)

+2  A: 
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;
}
KP
+1  A: 

To get the most recent enrollment for each course a student has taken, I'd use something like:

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

Is that what you're asking for?

kvb