Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a IQueryable with NHibernate and I would like to have an linq query to sum an specific column, but, when my condition on Where method give me an empty result I do not want to get an exception, but I would not like to hit an query to get all records and after it sum on memory, I would like something like coalese sql command, for sample:

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

I have 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 you.

like image 921
Felipe Oriani Avatar asked Apr 26 '13 17:04

Felipe Oriani


1 Answers

You need to cast Value to a nullable type.

For example, assuming Value is an int property:

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

Since a Sum() on a nullable enumerable will return null for an empty source, the coalesce operator (??) takes care of returning 0 when that happens.

like image 54
Diego Mijelshon Avatar answered Oct 15 '22 20:10

Diego Mijelshon