c# - LINQ - 加入 Group By 并获得平均值

标签 c# linq-to-entities

SQL:

SELECT DeptId,avg(Marks) FROM StudentTb s
JOIN StudInDepartment d on s.StudentId = d.StudentId
GROUP BY DeptId

转换为 Linq:

  var deptRpts =         from s in this.ObjectContext.StudentTb
                         join d in this.ObjectContext.StudInDepartment on s.StudentId equals d.StudentId  
                         group s by d.DeptId into grp
                         select new {
                             DeptId = grp.Key,
                             AverageMarks = grp.Average(ed=>ed.Marks)
                         };

得到一个空的结果列表。

在 Debug模式下扩展结果集时,显示错误函数评估超时

需要这方面的帮助。

最佳答案

查询按原样工作得很好,至少在我的模型中我只是拼凑在一起......它可能与数据库的结构有关....在我的模型中我的学生 ID 是外国的StudInDepartment (ha!) 表的关键,甚至这个简化的查询也能正常工作

var deptRpt2 = from d in ctx.StudInDepartment
   group d by d.DeptId into grp
   select new {
      Dept = grp.Key,
      AverageMarks = grp.Average(ed=>ed.StudentTb.Marks)
   };

您收到的消息“函数计算超时”可能是 Visual Studio debugger issue ,那里帮不了你,stackoverflow 上还有其他线程也在讨论它。

关于c# - LINQ - 加入 Group By 并获得平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6929136/

相关文章:

c# - 将 Func<> 传递给 Select

c# - WPF:向窗口添加用户控件

c# - Expression.Constant(value, type) 类型未知。如何定义类型

c# - Linq 通过层次结构递归

c# - linq 加入 guid 和字符串列

c# - gRPC c# 文件下载/上传 + Web 客户端

c# - 在linux上用c代码调用c#代码的最佳方法是什么

Linq - 如何将 "where condition"存储在变量中

linq-to-entities - LINQ to Entities无法识别 'System.String ToString()'方法

c# - DateTime 对象 Entity Framework 上的动态 LINQ OrderBy 日期