如何使用linq与聚合,加入和分组

时间:2018-04-24 17:55:18

标签: c# linq

我试图通过ID和名称来获得餐厅评级的平均值 退伍军人

审核课程

  public int ReviewId { get; set; }
        public double   Rating { get; set; }
        [ForeignKey("ResterauntId")]
        Resteraunt  Resteraunt { get; set; }
        public int ResterauntId { get; set; }

Resteraunt课程

  public int ResterauntId { get; set; }
        public string Name { get; set; }

        public virtual ICollection<Review> Reviews { get; set; }
        public virtual Review  reviews{ get; set; }

这是我尝试过的。但是这不会编译[g.Key.Rating.Average()] 而且我不知道如何在没有按名称分组的情况下选择名称

var ratings = (from rev in reviewsList
                 join res in resteraunts on rev.ResterauntId equals
                 res.ResterauntId

                 group new { rev, res } by new { res.ResterauntId, rev.Rating } into g

                 select new { Rating = g.Key.Rating, AveraRating =   g.Key.Rating.Average() }).ToList();

1 个答案:

答案 0 :(得分:1)

您需要按餐厅(ID)分组并平均每个的评级。由于LINQ具有Group Join,因此您只需使用join进行分组:

var avgRatings = (from res in resteraunts
                  join rev in reviewsList on res.ResterauntId equals
                  rev.ResterauntId into revj
                  select new { res.ResterauntId, AveraRating = revj.Average(r => r.Rating) }).ToList();

仔细查看您的(部分)课程,我发现您显然正在使用实体框架,在这种情况下您不需要手动加入:

var avgRatings = (from res in resteraunts
                  select new {
                      res.ResterauntId,
                      AveraRating = res.Reviews.Average(r => (double?)r.Rating)
                  }).ToList();

感谢@gnud。{/ 1>对Average的改进