代码之家  ›  专栏  ›  技术社区  ›  kristian

LINQ-分组和聚合

  •  2
  • kristian  · 技术社区  · 15 年前

    如果我有这三个班:

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

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

    但是,如果一个学生不止一次注册一门课程,我如何只显示每门课程的最新注册信息?

    我假设我需要按课程分组并过滤什么地方的入学日期=最高(入学日期)或类似的内容?

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

    2 回复  |  直到 14 年前
        1
  •  2
  •   KP.    15 年前
    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;
    }
    
        2
  •  1
  •   kvb    15 年前

    要获取学生所学每门课程的最新注册信息,我将使用如下内容:

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

    这就是你想要的吗?