简体   繁体   English

如何使用Joins Linq查询返回子集合

[英]How to return a child collection with joins linq query

I'm trying to figure out how to get a sub-collection, within a linq query. 我试图弄清楚如何在linq查询中获取子集合。 Basically I have courses, which have multiple schedules, but when I try the query below, it returns multiple objects, for each course, because the schedules are not a collection. 基本上我有一门课程,有多个时间表,但是当我尝试下面的查询时,它为每个课程返回多个对象,因为时间表不是一个集合。

 public JsonResult Required(int programId, int departmentId)
 {
        var courses = (from r in context.ProgramRequiredCourses
                       join c in context.IAUClasses on r.ClassId equals c.id
                       join s in context.IAUClassSchedules on c.id equals s.classId
                       join d in context.IAUDepartments on c.mainDepartmentId equals d.id                          
                       where r.ProgramId == programId && d.id == departmentId
                       select  new RequiredCourse{
                            Department = d,
                            Course = c,
                            Schedule = s
                       }).AsEnumerable().Distinct(new DistinctCourseComparer());
        return Json(courses, JsonRequestBehavior.AllowGet);
  }

**Supporting code ** **支持代码**

I know the Schedule in the RequiredCourse class should be changed to an IEnumerable, but not sure how to go about populating it. 我知道RequiredCourse类中的Schedule应该更改为IEnumerable,但是不确定如何填充它。

public class RequiredCourse
{
    public IAUClass Course { get; set; }
    public IAUClassSchedule Schedule { get; set; }
    public IAUDepartment Department { get; set; }
}

public class DistinctCourseComparer : IEqualityComparer<RequiredCourse>
{
    public bool Equals(RequiredCourse x, RequiredCourse y)
    {            
        return x.Course.id == y.Course.id &&
               x.Course.className == y.Course.className;
    }

    public int GetHashCode(RequiredCourse obj)
    {
        return obj.Course.id.GetHashCode() ^
               obj.Course.className.GetHashCode();
    }
}

It sounds like you're asking for a group join: 听起来您正在要求加入群组:

from r in context.ProgramRequiredCourses
join c in context.IAUClasses on r.ClassId equals c.id
join s in context.IAUClassSchedules on c.id equals s.classId into classSchedules
join d in context.IAUDepartments on c.mainDepartmentId equals d.id
where r.ProgramId == programId && d.id == departmentId
select new
{
    Department = d,
    Course = c,
    Schedules = classSchedules
}

Take special note of the into classSchedules part of the query. 特别注意查询的into classSchedules部分。 Instead of outputting a new row for each schedule, it will group all the schedules together, per class, into the IEnumerable<IAUClassSchedule> classSchedules 而不是为每个日程表输出新行,而是将每个类将所有日程表分组在一起,成为IEnumerable<IAUClassSchedule> classSchedules

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM