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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With