在 LINQ 查询中连接列表
我的数据结构是这样设置的
- 一个用户使用多个模块
- 一个模块包含多个课程
关系如下:
如何获取用户参加的课程列表?
我现在的查询是:
var courses = (from ClassEnrollment enrolment in entities.ClassEnrollment
where enrolment.UserID == UserID
join Module module in entities.Module
on enrolment.ModuleID equals module.ID
select module.Course
).ToList();
但是,这不会产生课程列表,而是课程列表的列表。
如何将此查询扁平化为不同课程的列表?
My data structure is set up this way
- A user takes a number of modules
- A module contains a number of courses
Here's how the relationship looks like:
How do I get a list of courses the user takes?
The query I have now is:
var courses = (from ClassEnrollment enrolment in entities.ClassEnrollment
where enrolment.UserID == UserID
join Module module in entities.Module
on enrolment.ModuleID equals module.ID
select module.Course
).ToList();
However, this doesn't result in a list of courses, but rather a list of list of courses.
How can I flatten this query to a list of distinct courses?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
根据您的数据结构屏幕截图,
ClassEnrollment
和Module
之间存在一对多关系,以及名为Module
的导航属性。Module
和Course
之间还存在多对多关系,但导航属性应称为Courses
。给定您的代码,您想要这样的内容:但是,您的问题提到了一个用户:
一个用户学习了多个模块
,如何获取用户学习的课程列表?< /代码>。不过,我在其他地方没有看到任何 User 实体,所以如果您能澄清一下就好了。顺便说一句,您正在使用 LINQ-to-SQL 吗?
According to your data structure screenshot, you have a one-to-many relationship between the
ClassEnrollment
andModule
, as well as navigational property calledModule
. You also have a many-to-many relationship betweenModule
andCourse
, but the navigational property should be calledCourses
. Given your code, you want something like this:Your question, however, mentions a user:
A user takes a number of modules
,How do I get a list of courses the user takes?
. I don't see any User entity anywhere else, though, so it would be nice if you could clarify. Are you using LINQ-to-SQL, btw?像这样的事情:
Something like this:
使用 SelectMany。
Use SelectMany.
您可以使用
course.SelectMany(c => c);
在查询中,您不需要显式指定范围变量的类型
,或者您可以将课程加入查询
You can use
courses.SelectMany(c => c);
In your query you don't need explicitly specify the type for the range variables
Or you can join course to the query