15

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?

4

5 回答 5

13

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;
于 2009-08-24T13:59:50.967 回答
6

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)

于 2009-08-24T14:11:49.237 回答
3
var outputIndicatorSum = (from OutputIndicatorTable in objDataBaseContext.Output_Indicators
                                          where OutputIndicatorTable.Output_Id == outputId
                                          select (int?)OutputIndicatorTable.Status).Sum();
                int outputIndicatorSumReturn = Convert.ToInt32(outputIndicatorSum);
                return outputIndicatorSumReturn;

You can explicitly type cast non-nullable varaible into nullable type. i.e, select (int?)OutputIndicatorTable.Status).Sum();

于 2013-05-08T13:14:57.903 回答
1

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);
于 2009-08-24T14:00:16.740 回答
-1

If you would like the result without two queries try:

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

If you want zero instead of null as the result of this query use:

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

于 2013-03-28T15:01:18.987 回答