我想在我的数据库中找到最好的五家餐馆。数据库的结构使我的linq查询复杂化。
这就是我的工作方式,我有一张表“评论”,其中包含我餐馆的外键,我有三种选择,可以在1到5之间进行投票。
表示例:
- idRestaurant
- ratingOne
- ratingTwo
- ratingThree
因此,我会将餐厅的平均分为三个音符
例如,如果我在表格中有一些记录
idRestaurant 1 - RatingOne 2 - RatingTwo 2 - RatingThree - 2
idRestaurant 1 - RatingOne : 4 - RatingTwo : 4 - RatingThree - 4
idRestaurant 2 - RatingOne : 3 - RatingTwo : 3 - RatingThree - 3
idRestaurant 2 - RatingOne : 4 - RatingTwo : 4 - RatingThree - 4
idRestaurant : 3 - RatingOne 1 - RatingTwo 1 - RatingThree - 1
idRestaurant : 3 - RatingOne 1 - RatingTwo 1 - RatingThree - 1
idRestaurant : 4 - RatingOne 1 - RatingTwo 1 - RatingThree - 1
idRestaurant : 4 - RatingOne 1 - RatingTwo 1 - RatingThree - 1
idRestaurant : 4 - RatingOne 1 - RatingTwo 1 - RatingThree - 1
idRestaurant : 4 - RatingOne 5 - RatingTwo 5 - RatingThree - 5
我希望我的LINQ的结果向我发送一个idRestaurants列表,按总分顺序排列,没有重复的餐厅 例如: {2,1,4,3}
我有以下查询
var restosss = (from w in db.restos_cote
group w by w.idRestoSuccursale into g
select new
{
idRestoSuccursale = g.Key, Restos = g
});
但它也需要按平均分数排序。
答案 0 :(得分:0)
三个值的平均值只是val1 + val2 + val3 / 3
然后您可以在此计算中使用Average
。
var restosss = (from w in db.restos_cote
group w by w.idRestoSuccursale into g
select new
{
idRestoSuccursale = g.Key, Restos = g
avgRating = g.Average(x => (x.RatingOne + x.RatingTwo + x.RatingThree) / 3.0)
})
//if you want "best ratings" first, else use OrderBy
.OrderByDescending(m => m.avgRating)
//take only the 5 best ratings
.Take(5);
顺便说一句,如果您只想要正确的排序,但不使用平均结果,则不需要除以3.0