Extrakun
Extrakun

Reputation: 19325

Concatenating lists inside a LINQ query

My data structure is set up this way

Here's how the relationship looks like: enter image description here

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?

Upvotes: 1

Views: 574

Answers (4)

volpav
volpav

Reputation: 5128

Something like this:

var courses = from ClassEnrollment enrolment in entities.ClassEnrollment
              from module in entities.Module
              where enrolment.ModuleID equals module.ID && enrolment.UserID equals UserID
              select module.Course

Upvotes: 1

Nasmi Sabeer
Nasmi Sabeer

Reputation: 1380

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

var query = from enrolment in entities.ClassEnrollment
            join module in entities.Module on enrolment.ModuleID equals module.ID
            join course in entities.Course on module.CourseID equals course.ID
            where enrolment.UserID == UserID
            select course;

var course = query.ToList();

Upvotes: 1

Yakimych
Yakimych

Reputation: 17752

According to your data structure screenshot, you have a one-to-many relationship between the ClassEnrollment and Module, as well as navigational property called Module. You also have a many-to-many relationship between Module and Course, but the navigational property should be called Courses. Given your code, you want something like this:

var courses = entities.
              ClassEnrollment.
              Where(e => e.UserID == UserID).
              SelectMany(e => e.Module.Courses).
              ToList();

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?

Upvotes: 2

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174369

Use SelectMany.

Upvotes: 1

Related Questions