我有以下语句,使用 GroupBy
计算最大值,并使用 Any()
来检查是否有任何记录,但是这个查询仍然返回 Sequence contains no elements exception
错误。有什么想法吗?
baseQuery = baseQuery.Where(s => s.LearningActions.SelectMany(la => la.ProgressUpdates)
.GroupBy(d => d.LearningActionId)
.Select(a => a.Any() ? new { Max = a.Max(d => d.Progress) } : new { Max = 0})
.Average(d => d.Max) < averageProgress.GetValueOrDefault());
以防万一,这里是 baseQuery
。
IQueryable<Submission> baseQuery = _context.Submissions
.Where(s => s.ReviewRoundId == reviewRoundId);
我也尝试了以下替代方案:
baseQuery = baseQuery.Where(s => s.LearningActions.SelectMany(la => la.ProgressUpdates)
.GroupBy(d => d.LearningActionId)
.Select(a => new { Max = (int?) a.Max(d => d.Progress) })
.Average(a => a.Max.GetValueOrDefault()) < averageProgress.GetValueOrDefault());
但它会引发以下错误:
查询源(来自 [a] 中的 LearningActionProgress d)已经与表达式相关联。
更新
以下代码可行:
baseQuery = baseQuery.Where(s => s.LearningActions.SelectMany(la => la.ProgressUpdates)
.GroupBy(d => d.LearningActionId)
.Select(a => a.Max(d => d.Progress)).Any() ?
s.LearningActions.SelectMany(la => la.ProgressUpdates)
.GroupBy(d => d.LearningActionId)
.Select(a => a.Max(d => d.Progress)).Average() > averageProgress.GetValueOrDefault() : false); // Here a can be null or empty
我不得不做这个检查 s.LearningActions.SelectMany(la => la.ProgressUpdates).GroupBy(d => d.LearningActionId).Select(a => a.Max(d => d.Progress)).Any()
但是,我觉得有点冗长,有什么更好的方式可以包含这个 check
吗?
a?
给我的是...可能不包含空传播运算符
。 - renakrea.Any() ? a : 0
。 - karas.LearningActions.SelectMany(la => la.ProgressUpdates) .GroupBy(d => d.LearningActionId) .Select(a => a.Max(d => d.Progress)).Any()
就可以工作了。我不明白为什么a.Any()
不像你建议的那样工作... - renakreAverage
中使用的任何对象都不包含任何元素。问题出现在更高一级。Select
没有返回任何元素来执行Average
。 - Mihaeru