【发布时间】:2019-11-24 11:03:30
【问题描述】:
我是 LINQ 新手,我需要编写一个 LINQ 查询来返回每个项目的成绩,称为 notet 也是所有 notes 的平均值。
这是我的查询:
`var query = _context.Set<EvaluationResult>()
.Include(x => x.RatingLevel)
.Include(x => x.Skill)
.Include(x => x.Evaluation)
.ThenInclude(y => y.Project)
.ThenInclude(z => z.ProjectRatingLevels)
.ThenInclude(a => a.RatingLevel)
.Include(y => y.Evaluation.Project)
.ThenInclude(y => y.Degree)
.Where(x => x.Evaluation.Project.DegreeId == QueriedDegreeId)
.GroupBy(i => new { project = i.Evaluation.Project })
.Select(g => new
{
project = g.Select(y => y.Evaluation.Project.Label)
.Distinct().FirstOrDefault(),
note = Math.Round(((g.Sum(y => (double)y.Skill.Weight * (double)y.RatingLevel.Rate) /
g.Sum(y => (double)y.RatingLevel.Rate)) * 100) /
(double)g.Key.project.ProjectRatingLevels
.Select(z => z.RatingLevel.Rate)
.Max(), 2, MidpointRounding.AwayFromZero)
});
结果如下:
[
{
"project": "Projet 1",
"note": 42.86
},
{
"project": "Projet 2",
"note": 41.67
},
{
"project": "Projet 3",
"note": 46.67
}
]
我想要添加另一个值,average,它只是所有“注释”值的平均值,就像这样(星号只是为了强调):
[
{
"project": "Projet 1",
"note": 42.86,
**"average": 43.73**
},
{
"project": "Projet 2",
"note": 41.67,
**"average": 43.73**
},
{
"project": "Projet 3",
"note": 46.67,
**"average": 43.73**
}
]
我的问题
我一直在尝试计算所有返回的 notes 的平均值。我不知道如何进行。我尝试在note 和project 之后在我的Select 中添加一个average 键,以重用note 查询,如下所示:
average = g.Average(Math.Round(((g.Sum(... etc
但这给了我类型错误:CS1929 'IGrouping<<anonymous type: Project project>, EvaluationResult>' does not contain a definition for average 'Average'。所以我完全不知道该怎么做。
有人能指出我正确的方向吗?我是否遗漏了一些东西,比如需要使用 Key 或其他东西?
【问题讨论】:
标签: c# visual-studio entity-framework linq