我正在尝试使用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。
答案 0 :(得分:5)
你可以尝试
(from surveyResult in
surveyResultsFromChats
where surveyResult.FirstScoreNPS.HasValue && surveyResult.GroupID == gr &&
surveyResult.FirstScoreNPS >= 9
select surveyResult.FirstScoreNPS).
Select(score => score.Value ?? 0).Sum();