Does not get an exception when the collection is empty with the Sum and Nhibernate method

I have IQueryablewith NHibernate, and I would like to have a linq query to summarize a specific column, but when my condition in the method Wheregives me an empty result, I do not want to get an exception, but I would not want to hit the request to get all the records, and after summing it from memory I would like something like coalesesql command, for a sample:

// I get exception when its empty
var query = MyQueryable()
              .Where(x => x.IsDone)
              .Select(x => x.Value)
              .Sum(); 

I need to do something like this:

// I get 0, its ok, but ToList(), list all records on memory, 
// I just want to get a single value

var query = MyQueryable()
               .Where(x => x.IsDone)
               .Select(x => x.Value)
               .ToList()
               .Sum(); 

Is there any way?

Thank.

+5
source share
1 answer

You need to point Valueto a type with a null value.

For example, if it Valueis a property int:

var result = MyQueryable()
                 .Where(x => x.IsDone)
                 .Select(x => (int?)x.Value)
                 .Sum()
             ?? 0;

a Sum() null , coalesce (??) 0, .

+7

All Articles