Linq to SQL - 即使在0时获取count()的查询

时间:2012-07-17 01:40:33

标签: c# .net linq-to-sql

我有这个问题:

(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 },
};

好的以上现在是正确的,很抱歉这个混乱!

2 个答案:

答案 0 :(得分:4)

这被称为Left Outer Join。在这种情况下,即使没有 Sick Days ,每个 Student 也是必需的。因此,我们将从学生开始,在病假时执行左外连接,然后返回与您指定的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)
        };

答案 1 :(得分: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)

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