Linq Group同时避免Div / 0

时间:2013-08-19 14:08:02

标签: c# asp.net-mvc asp.net-mvc-3 linq

我有一个模型,我正在尝试计算加权平均值:

  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子句,因此我可以按Date / AnalystId等进行分组。

是否可以组合两个LINQ语句,以便我可以这样做,同时如果weightSum = 0,仍然可以避免DIV / 0?

谢谢,Mark

1 个答案:

答案 0 :(得分:3)

使用如下表达式:

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();