Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq2SQL: Always get .Sum() to return 0 instead of null

Is there any way (through a extention mechanism?) to get the Sum() function to allways return 0.

My workaround now is to write like this, but I'm hoping there's a better solution?

((int?)e.CampaignCodes.Sum(f => f.Enquiries.Count()) ?? 0),
like image 779
Niels Bosma Avatar asked Dec 31 '22 05:12

Niels Bosma


2 Answers

Your workaround there is a good one. Why don't you write an extension method for IEnumerable similar to Sum called something like SumOrDefault. Then you could just reuse your extension method and you will not have to see the workaround.

Your extension method will be very simple and just use the exact code from your workaround.

like image 73
Brendan Enrick Avatar answered Jan 13 '23 20:01

Brendan Enrick


That's a pretty good way actually. I think the better question is why is it null to begin with? Unless the entity you're invoking the sum on is null, the query should always return 0. It might be a better solution to see whether your entity is valid at the start as opposed to forcing the sum to always return 0 -- Null means there's a problem.

like image 38
MunkiPhD Avatar answered Jan 13 '23 20:01

MunkiPhD