简体   繁体   English

如何将linq与Aggregation,join和Group by一起使用

[英]How to use linq with an aggregate , join and Group by

I am trying to get averages of restaurant Ratings by id along with the Names of resteraunts. 我正在尝试通过ID以及餐馆名称来获取餐厅评分的平均值。

Review Class 复习班

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

Resteraunt class 餐饮班

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

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

Here is what I tried. 这是我尝试过的。 However this will not compile [g.Key.Rating.Average()] And I don't know how to select the names without grouping by name as well 但是,这不会编译[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();

You need to group by restaurant (id) and average the ratings for each. 您需要按餐厅(id)分组并平均每个餐厅的评分。 Since LINQ has Group Join, you can just use the join to get the grouping: 由于LINQ有集团加入,你可以只使用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();

Looking more closely at your (partial) classes, I see you are apparently using Entity Framework, in which case you don't need to manually join: 仔细查看您的(部分)类,我发现您显然正在使用Entity Framework,在这种情况下,您无需手动加入:

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

Improvement on Average thanks to @gnud. 由于@gnud, Average有所提高。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM