2

我正在尝试使用 Linq 计算可空 int 的总和。我的查询如下所示:

int? surveysPromotersFromChatsGroup = (from surveyResult in surveyResultsFromChats
                                            where surveyResult.FirstScoreNPS.HasValue && surveyResult.GroupID == gr && surveyResult.FirstScoreNPS >= 9
                                            select surveyResult.FirstScoreNPS).Sum();

FirstScoreNPs 字段是一个可为空的 int。我的问题是总和总是返回 null 无论如何。我看不出这背后的逻辑。我检查并确定某些实体在该字段中确实具有值,并且 sum 方法应该总结这些值。

我尝试的另一种方法是这样的:

int surveysPromotersFromChatsGroup = (from surveyResult in surveyResultsFromChats
                                      where surveyResult.FirstScoreNPS.HasValue && surveyResult.GroupID == gr && surveyResult.FirstScoreNPS >= 9
                                      select surveyResult.FirstScoreNPS).Sum(score => score.Value);

但我得到一个异常“linq null 值不能分配给具有类型的成员”。

没有办法使用 linq 总结该字段中的非空值吗?

surveyResultsFromChat 实际上来自另一个查询:

                var surveyResultsFromChats = from surveyResult in db.SurveyResults
                                    join survey in db.Surveys on surveyResult.SurveyID equals survey.SurveyID
                                    join userGroup in db.UserGroupMaps on surveyResult.UserID equals userGroup.UserID
                                    where surveyResult.CreatedDate >= startDate && surveyResult.CreatedDate <= endDate && surveyResult.UserID.HasValue && surveyResult.ChatSessionID.HasValue
                                    select new { surveyResult.ResultID, survey.BrandID, userGroup.GroupID, surveyResult.CompletedDate, surveyResult.FirstScoreNPS };

我的模型中的 FirstScoreNPS 是一个 Nullable int。

4

1 回答 1

5

你可以试试

(from surveyResult in
 surveyResultsFromChats
where surveyResult.FirstScoreNPS.HasValue && surveyResult.GroupID == gr && 
surveyResult.FirstScoreNPS >= 9
   select surveyResult.FirstScoreNPS).
Select(score => score.Value ?? 0).Sum();
于 2012-09-27T14:24:52.143 回答