0

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

  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?

谢谢,马克

4

1 回答 1

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();
于 2013-08-19T14:20:24.333 回答