0

我有这个查询:

(from a in SickDays
    join b in Class.Where(p => p.ID == myId) on a.Class_ID equals b.ID
    join c in Student on a.Student_ID equals c.ID
    group a by new { c.Name, c.Order } into ac
    select new { Count = ac.Count(), Name = ac.Key.Name, Order = ac.Key.Order }
).OrderBy(f => f.Order)

这将返回:

Count | Name | Order
    3 | Dave |     a
    2 | John |     b
    7 | Sally|     c

但是我希望它返回这个:

Count | Name | Order
    3 | Dave |     a
    2 | John |     b
    7 | Sally|     c
    0 | Mark |     d
    0 | Betty|     e

更新: 使用@sixlettervariables 示例,这就是学生、班级和病假日的样子:

var Students = new List<Student>()
{
    new Student { Id = 1, Name = "Al", Order = 'a' },
    new Student { Id = 2, Name = "Betty", Order = 'b' },
    new Student { Id = 3, Name = "Charles", Order = 'c' },
};

var Classes = new List<Class>()
{
    new Class { Id = 1, Title = "A100" },
    new Class { Id = 2, Title = "A200" },
};

var SickDays = new List<SickDay>()
{
    new SickDay { Id = 1, StudentId = 1, ClassId = 1 },
    new SickDay { Id = 2, StudentId = 1, ClassId = 1 },
    new SickDay { Id = 3, StudentId = 1, ClassId = 2 },
    new SickDay { Id = 4, StudentId = 1, ClassId = 2 },
    new SickDay { Id = 5, StudentId = 2, ClassId = 1 },
};

好的,以上内容现在是正确的,很抱歉造成混淆!

4

2 回答 2

4

这称为左外连接。在这种情况下,每个学生都需要,即使他们没有Sick Days。因此,我们将从学生开始,对病假执行左外连接,然后返回与您指定的 ID 匹配的课程数量:

var query =
    from s in Students
    join d in SickDays on s.ID equals d.Student_ID into gj
    from sd in gj.DefaultIfEmpty()
    group sd by new { s.Name, s.Order } into gg
    select
        new
        {
            Name = gg.Key.Name,
            Order = gg.Key.Order,
            Count = gg.Count(x => x != null && x.Class_ID == myId)
        };
于 2012-07-17T01:59:10.273 回答
0

所以你想要所有的学生,即使他们不在课堂上?那么我相信你需要一个左连接。使用 Linq,这是使用 DefaultIfEmpty() 实现的

试试这个?

(from a in SickDays
    join b in Class.Where(p => p.ID == myId) on a.Class_ID equals b.ID
    join c in Student on a.Student_ID equals c.ID
        into s
    from students in s.DefaultIfEmpty()
    group a by new { students.Name, students.Order } into ac
    select new { Count = ac.Count(), Name = ac.Key.Name, Order = ac.Key.Order }
).OrderBy(f => f.Order)

我希望这能让你朝着正确的方向前进。

于 2012-07-17T01:46:55.010 回答