林克在躲避Div/0时分组
本文关键字:0时 Div 躲避 林克 | 更新日期: 2023-09-27 18:28:16
我有一个模型,我试图计算加权平均值:
public class ObScore
{
public int ObScoreId { get; set; }
public int AnalystId { get; set; }
public DateTime Date { get; set; }
public int PossScore { get; set; }
public int Weight { get; set; }
}
我可以使用以下代码做到这一点:
//
// GET: /Test/
public ActionResult Test()
{
var scores = db.ObScores.ToList();
double weightedValueSum = scores.Sum(x=>x.PossScore * x.Weight);
double weightSum = scores.Sum(x => x.Weight);
if (weightSum != 0)
{
ViewBag.wa2 = weightedValueSum / weightSum;
}
return View();
}
然而,我希望能够添加GroupBy子句,这样我就可以按日期/AnalystId等进行分组。
有没有可能将这两个LINQ语句组合起来,这样我就可以做到这一点,同时如果weightSum=0,仍然可以避免DIV/0?
谢谢,Mark
使用以下表达式
div = weightSum != 0 ? weightedValueSum / weightSum : -1
最终应该是这样的:
var res = scores.GroupBy(p => p.Date.Year)
.Select(p => new {
Year = p.Key,
weightedValueSum = p.Sum(x => x.PossScore * x.Weight),
weightSum = p.Sum(x => x.Weight)
})
.Select(p => new {
Year = p.Year,
wa2 = p.weightSum != 0 ? p.weightedValueSum / p.weightSum : -1
})
.ToArray();
在完整的LINQ语法中,这应该或多或少相当于此
var res2 = (from p in scores
group p by p.Date.Year into p
let Year = p.Key
let weightedValueSum = p.Sum(x => x.PossScore * x.Weight)
let weightSum = p.Sum(x => x.Weight)
select new {
Year = Year,
wa2 = weightSum != 0 ? weightedValueSum / weightSum : -1
}).ToArray();