如何将左外连接添加到分组和求和LINQ查询

时间:2012-12-07 17:10:45

标签: c# linq

我有一张员工表:

EmployeeID  |  EmployeeName
---------------------------
1           |  Jack
2           |  Jill
3           |  Roger

和一个出现表:

OccurrenceID  |  EmployeeID  |  Points
--------------------------------------
1             |  1           |  5
2             |  2           |  3
3             |  1           |  1

我有一个有效的LINQ查询,它将两个表分组并汇总在一起:

groupedOccurrences = (from o in db.Occurrences.Include(o => o.Employee)
                      where o.OccurrenceDate >= beginDate
                         && o.OccurrenceDate <= endDate
                      group o by o.Employee.EmployeeName into g
                      select new OccurrenceByQuarter
                      {
                          Name = g.Key,
                          Total = g.Sum(o => o.Points)
                       });

产生此输出:

 Jack 6
 Jill 3

但我希望员工Roger在输出中显示0分。我尝试在LINQ查询中添加一个连接,如下所示:

groupedOccurrences = (from e in db.Employees
                      from o in db.Occurrences
                      join o in db.Occurrences on e.EmployeeID equals o.EmployeeID into j1
                      from j2 in j1.DefaultIfEmpty()
                      group j2 by e.EmployeeName into g
                      select new OccurrenceByQuarter
                      {
                          Name = g.Key,
                          Total = g.Sum(o => o.Points)
                      });

但我最终得到了大量夸大的分数(就像他们应该做的那样24倍)。

我还试图通过在我的OccurrencesByQuarter类中将Total的声明更改为public int? Total { get; set; }来获取Total,如果为null则返回0,但是当我尝试将LINQ查询更改为包含{{1我得到一个错误,说&#34;运算符?不能应用于int和int&#34;类型的操作数。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:6)

使用群组加入:

groupedOccurrences = (from e in db.Employees
                      join o in db.Occurrences.Where(x => 
                                  x.OccurrenceDate >= beginDate &&
                                  x.OccurrenceDate <= endDate)
                           on e.EmployeeID equals o.EmployeeID into g
                      select new OccurrenceByQuarter
                      {
                          Name = e.EmployeeName,
                          Total = g.Sum(x => (int?)x.Points) ?? 0
                      });

结果将是:

Jack  6
Jill  3
Roger 0

要为空组返回0,请将summa属性转换为nullable,然后应用null-coalescing运算符以返回默认值:g.Sum(x => (int?)x.Points) ?? 0