简体   繁体   中英

Use Linq to filter data from another table

I have a MovieReviewsDataContext context that includes a Movie and Review table.

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.

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

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.

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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