tags:

views:

636

answers:

3

I have a link 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 seperate query first to eliminate this situation before performing the sum?

+1  A: 

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;
Scott Ivey
This query enumerates the results twice...
Thomas Levesque
Although this does enumerate the results twice, My collections are small and I find this the most readable. So Have accepted it. Thanks everyone.
Si Keep
+1  A: 

Using Sum alone, this is impossible. As you indicated in your question, you will need to check for this situation before you call Sum:

var q = Level3Data.AsQueryable();
var duration = q.All(d => d.DurationMonths == null)
                   ? null
                   : q.Sum(d => d.DurationMonths);
Erik Forbes
Bah, less than a minute too late. Lol
Erik Forbes
+1  A: 

You can use Aggregate to provide custom aggregation code :

var items = Level3Data.AsQueryable();
var duration = items.Aggregate<D,int?>(null, (s, d) => (s == null) ? d.DurationMonths : s += (d.DurationMonths ?? 0));

(assuming the items in Level3Data are of type D)

Thomas Levesque