LINQ - joining multiple lists

前端 未结 3 376
猫巷女王i
猫巷女王i 2021-01-21 14:33

I\'ve looked at the 101 Linq Samples here but I can\'t see anything like this in that list. If I\'m just not seeing a relevant example there, please link to it.

If I ha

相关标签:
3条回答
  • 2021-01-21 15:07

    Not an explicit answer, but perhaps implicitly helpful building your system.

    Have you considered a richer domain model like so:

    class Student { int id; string name; IEnumerable<Enrolment> enrolments }
    class Course { int id, string name; }
    class Enrolment { Student student; Course course; }
    

    ?

    The Student class could then have a method GetEnroledCourses() like so:

    public IEnumerable<Course> GetEnroledCourses()
    {
       return enrolements.Select(enrolement => enrolement.Course).ToList().AsReadonly();
    }
    

    A model that's merely a one-to-one mapping to the database suffice in some contexts, but if you have complex business logic such an «anemic domain model» might bite you.

    0 讨论(0)
  • 2021-01-21 15:19
    var courses = (from course in courseList 
        join enr in enrolmentList on enr.courseId equals course.id 
        where enr.studentId = <student id variable> 
        select course);
    
    0 讨论(0)
  • 2021-01-21 15:31

    How about:

    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;
    }
    
    0 讨论(0)
提交回复
热议问题