gpt4 book ai didi

c# - LINQ - 分组和聚合

转载 作者:行者123 更新时间:2023-11-30 22:50:06 25 4
gpt4 key购买 nike

如果我有这 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;
}

我可以列出学生注册的所有类(class)。

但是,如果学生多次注册一门类(class),我该如何只显示每门类(class)的最新注册?

我假设我需要按类(class)分组并过滤 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;
}

关于c# - LINQ - 分组和聚合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/756503/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com