简体   繁体   English

使用Linq过滤另一个表中的数据

[英]Use Linq to filter data from another table

I have a MovieReviewsDataContext context that includes a Movie and Review table. 我有一个MovieReviewsDataContext上下文,其中包括一个Movie和Review表。

I would like to retrieve the top 15 movies that have at least two reviews and that have an average review better than the average movie reviews. 我想检索前15部电影,这些电影至少有两个评论,并且平均评论要优于平均电影评论。

The code I was able to write: 我能够编写的代码:

 var topMovies = movieReviewsDataContext.Movies
                .Where(m => m.Reviews.Count > 2)
                .Where(m => m.Reviews.Average(r => r.rating) > 
                    movieReviewsDataContext.Reviews.Average(r => r.rating))
                .Take(15);

checks only if the average rating for the movie is higher than the global average. 仅检查电影的平均评分是否高于全球平均水平。 How do I change it to compare it to the average of all the movies' average? 如何更改它以将其与所有电影的平均值进行比较?

Assuming you have a 假设你有一个

public virtual Movie Movie {get;set;} property in Review entity Review实体中的public virtual Movie Movie {get;set;}属性

If you have not that property, you have probably something else (an int MovieId for example) to discriminate the review's movie, which you can use in the group by clause. 如果没有该属性,则可能还有其他内容(例如int MovieId )可以区分评论的电影,您可以在group by子句中使用它。

var averageOfMovieAverages = movieReviewsDataContext
                                         .GroupBy(x => x.Movie.Id)
                                         //.Where(x => x.Count() > 2) if you need this clause
                                         .Select(x => x.Average(m => m.rating))
                                         .Average();

which you can use in your query (you can also do this directly in your query, but I just created a variable for readability). 您可以在查询中使用它(您也可以直接在查询中执行此操作,但是我只是为了便于阅读而创建了一个变量)。

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

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