Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a linq Sum return null if the summed values are all null

Tags:

linq

sum

nullable

I have a LINQ query that looks like this...

var duration = Level3Data.AsQueryable().Sum(d => d.DurationMonths);

If all the d.DurationMonths values are null the Sum returns 0. How can I make the Sum return null if all the d.DurationMonths are null? Or do I need to run a separate query first to eliminate this situation before performing the sum?

like image 245
Simon Keep Avatar asked Aug 24 '09 13:08

Simon Keep


1 Answers

Along with the previous suggestion for an extension method - you could use a ternary operator...

var duration = Level3Data.AsQueryable().Any(d => d.DurationMonths.HasValue) 
               ? Level3Data.AsQueryable().Sum(d => d.DurationMonths) 
               : null;
like image 193
Scott Ivey Avatar answered Oct 11 '22 07:10

Scott Ivey