I'm trying to calculate average based on the sum of columns and how many there are.
Each movie can have a movierating, I'm trying to sum the movieratings together and then divide them by the amount of ratings to get the average rating for a movie.
(reviews.Where(w => w.MovieID == m.MovieID).Sum(o => o.MovieRating)) / reviews.Where(z => z.MovieID == m.MovieID).Count();
But the problem is if the count is 0. What can I do about it?
How about using LINQs built in
reviews .Where(z => z.MovieID == m.MovieID) .Select(z => z.MovieRating) .DefaultIfEmpty(0) .Average()
To have the query fully run on the server (depending, I guess, on your database server):
reviews .Where(z => z.MovieID == m.MovieID) .Average(z => (decimal?)z.MovieRating) ?? 0