获取产品和产品类别的评分

时间:2018-06-27 06:59:30

标签: c# linq

我有三个表格:产品,类别和等级。我正在尝试获得产品和产品类别的平均评分。这是我所做的,但是它给了我相同的评级,该评级仅适用于产品而不适用于其类别。

 public class Ratings
 {
     public int RatingId { get; set; }
     public int Rating { get; set; }
     public int ProductId { get; set; }
 }

 public class Category
 {
     public int CategoryId { get; set; }
     public string Name { get; set; }
 }

 public class Products
 {
     public int ProductId { get; set; }
     public string Name { get; set; }
     public int CategoryId { get; set; }
 }

这些是我的查询

var tmparray = db.Rating.Include(n => n.Products)
           .Where(x => x.Products.CategoryId == CategoryId).Take(1)
           .GroupBy(p => p.ProductsId, o => o.Rating)
           .Select(p => new
           {
               ProductsId = p.Key,
               AverageCategory = p.Average()
           });

var tmparray2 = db.Ocjene
          .GroupBy(p => p.ProductsId, o => o.Rating)
          .Select(p => new
          {
              ProductsId = p.Key,
              Average = p.Average()
          });

1 个答案:

答案 0 :(得分:1)

每个Rating都知道其Product,每个Product都知道其Category,因此我们可以按类别输入并返回到Rating。然后将结果按类别分组。

var ratingsByCategory = from c in categories
                        join p in products on c.CategoryId equals p.CategoryId
                        join r in ratings on p.ProductId equals r.ProductId
                        group new 
                        { 
                            categoryId = c.CategoryId,
                            rating = r.Rating
                        } by c.CategoryId into g
                        select new
                        {
                            categoryId = g.Key,
                            rating = g.Average(r=>r.rating)
                        };

在此处共享运行示例:.Net Fiddle