【发布时间】:2015-05-22 17:08:56
【问题描述】:
如果我使用以下代码,我会得到一个学习课程 1 和课程 2 的学生列表。(这几乎是我想要的。)
IQueryable<Student> filteredStudents = context.Students;
filteredStudents = filteredStudents
.Where(s => s.Courses.Select(c => c.CourseID).Contains(1));
filteredStudents = filteredStudents
.Where(s => s.Courses.Select(c => c.CourseID).Contains(2));
List<Student> studentList = filteredStudents.ToList<Student>();
但是,如果我尝试在 foreach 循环中执行此操作(如下面的代码所示),那么我会得到一个在循环中注册最后一门课程的所有学生的列表。
IQueryable<Student> filteredStudents = context.Students;
foreach (Course course in filter.Courses) {
if (course != null) {
filteredStudents = filteredStudents
.Where(s => s.Courses.Select(c => c.CourseID).Contains(course.CourseID));
}
}
List<Student> studentList = filteredStudents.ToList<Student>();
这种行为让我很困惑。谁能解释为什么会这样?以及如何绕过它?谢谢。
【问题讨论】:
-
.Select(s => s)是不需要的,Student已经默认选中了
标签: c# entity-framework linq-to-entities