试图将Linq除以零

时间:2018-05-24 12:19:04

标签: c# linq

我试图根据列的总和以及有多少列来计算平均值。

每部电影都可以进行电影制作,我试图将影片合并在一起,然后将它们除以评分数量,以获得电影的平均评分。

(reviews.Where(w => w.MovieID == m.MovieID).Sum(o => o.MovieRating)) / reviews.Where(z => z.MovieID == m.MovieID).Count();

但问题是如果计数为0.我该怎么办呢?

6 个答案:

答案 0 :(得分:7)

如何使用Average函数内置的LINQ?

reviews
    .Where(z => z.MovieID == m.MovieID)
    .Select(z => z.MovieRating)
    .DefaultIfEmpty(0)
    .Average()

让查询在服务器上完全运行(我猜,在数据库服务器上):

reviews
    .Where(z => z.MovieID == m.MovieID)
    .Average(z => (decimal?)z.MovieRating) ?? 0

答案 1 :(得分:5)

您可以使用

var ratingList = reviews
   .Where(z => z.MovieID == m.MovieID)
   .Select(z => z.MovieRating)
   .ToList();
if(ratingList.Count > 0)
{
   double result = ratingList.Sum() / ratingList.Count;
}

答案 2 :(得分:1)

double? score = reviews
   .Where(w => w.MovieID == m.MovieID)
   .Average(w => (double?) w.MovieRating)
   // ?? 0   // optional: pick a default when Average returns null
   ;

答案 3 :(得分:0)

如果条件如下,请使用内联:

var avr = (from a1 in reviews
           where a1.MovieID == m.MovieID
           group a1 by a1.MovieID into g
           select new
           {
               avr = g.count() == 0 ? 0 : g.sum(r => r.MovieRating) / g.count()
           }).FirstOrDefault().avr;

答案 4 :(得分:-1)

我想做一个单独的查询(因为我们可能正在处理数据库,每个查询都有成本"只是因为它是一个查询")而且所有的计算都是SQL端,所以我收回了一行(因为如果有1000条评论,我真的不需要下载所有这些评论......我想要他们MovieRating的总和及其数量。

// Based on https://stackoverflow.com/a/45144198/613130
var result = reviews
    .Where(x => x.MovieID == m.MovieID)
    .GroupBy(x => 1)
    .Select(x => ((double?)x.Sum(y => y.MovieRating)) / x.Count())
    .FirstOrDefault() ?? -1.0;

如果result没有评论,则-1.0将为MovieID。注意使用强制转换,否则我们可能会有一个整数除法(如果MovieRating是一个整数)。

请注意,如果找不到某行,则无法进行任何划分(因为不会有Group

SQL数据库上的等效查询应为

SELECT CAST(SUM(x.MovieRating) AS FLOAT) / COUNT(*) 
    FROM Reviews x 
    WHERE x.MovieID = @MovieID 
    GROUP BY 1

但事实上,EF以更复杂的方式翻译它:-)(在EF 6.2.0上测试):

SELECT 
    CAST( [GroupBy1].[A1] AS float) /  CAST( [GroupBy1].[A2] AS float) AS [C1]
FROM ( SELECT 
    [Filter1].[K1] AS [K1], 
    SUM([Filter1].[A1]) AS [A1], 
    COUNT([Filter1].[A2]) AS [A2]
    FROM ( SELECT 
        1 AS [K1], 
        [Extent1].[MovieRating] AS [A1], 
        1 AS [A2]
        FROM #Reviews AS [Extent1]
        WHERE [Extent1].[MovieId] = @p__linq__0
    )  AS [Filter1]
    GROUP BY [K1]
)  AS [GroupBy1]

答案 5 :(得分:-1)

不确定是否特别强调使用LINQ,但我更愿意将它全部放在for / foreach循环而不是多个LINQ中。否则下面会有用吗?

var matchingReviews = reviews.Where(w => w.MovieID == m.MovieID);
int matchingReviewCount = matchingReviews.Count();
if (matchingReviewCount  > 0)
{
    matchingReviews.Sum(o => o.MovieRating) / matchingReviewCount;
}
else
{
    //return default value?
}