3

我有一个员工表:

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

还有一个 Occurrences 表:

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 倍一样)。

我还尝试通过public int? Total { get; set; }在我的 OccurrencesByQuarter 类中将 Total 的声明更改为 null 来让 Total 返回 0,但是当我尝试将 LINQ 查询更改为包含时,Total = g.Sum(o => o.Points) ?? 0我收到一条错误消息,提示“操作员 ?? 无法应用到 int 和 int 类型的操作数”。

任何帮助将非常感激。

4

1 回答 1

7

使用组加入:

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空组,将汇总属性转换为可空,然后应用空合并运算符返回默认值:g.Sum(x => (int?)x.Points) ?? 0

于 2012-12-07T17:25:19.657 回答