简体   繁体   中英

Linq with sum with nullable int

I am trying to compute a sum of nullable int using Linq. My query looks like this:

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

FirstScoreNPs field is a nullable int. My problem is that the sum always return null no matter what. I can't see the logic behind this. I checked and I know for certain that some entities do have values in that field and the sum method should sum up those values.

Another approach that I tried is like this:

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

But I get an exception "linq the null value cannot be assigned to a member with type".

Isn't there a way to sum up the non null values from that field using linq?

The surveyResultsFromChat is actually from another query:

                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 in my model is an Nullable int.

you can try out

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

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