如何使用连接linq查询返回子集合

时间:2014-09-25 02:08:27

标签: c# .net json linq c#-4.0

我正试图弄清楚如何在linq查询中获取子集合。基本上我有多个时间表的课程,但是当我尝试下面的查询时,它会为每个课程返回多个对象,因为时间表不是一个集合。

 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);
  }

**支持代码**

我知道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();
    }
}

1 个答案:

答案 0 :(得分:2)

听起来你正在要求小组加入:

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
}

特别注意查询的into classSchedules部分。它不是为每个计划输出新行,而是将每个类的所有计划组合到IEnumerable<IAUClassSchedule> classSchedules