How to do Linq aggregates when there might be an empty set?

Posted by Shaul on Stack Overflow See other posts from Stack Overflow or by Shaul
Published on 2010-03-16T15:08:09Z Indexed on 2010/03/16 15:31 UTC
Read the original article Hit count: 239

Filed under:
|
|

I have a Linq collection of Things, where Thing has an Amount (decimal) property.

I'm trying to do an aggregate on this for a certain subset of Things:

var total = myThings.Sum(t => t.Amount);

and that works nicely. But then I added a condition that left me with no Things in the result:

var total = myThings.Where(t => t.OtherProperty == 123).Sum(t => t.Amount);

And instead of getting total = 0 or null, I get an error:

System.InvalidOperationException: The null value cannot be assigned to a member 
with type System.Decimal which is a non-nullable value type.

That is really nasty, because I didn't expect that behavior. I would have expected total to be zero, maybe null - but certainly not to throw an exception!

What am I doing wrong? What's the workaround/fix?

© Stack Overflow or respective owner

Related posts about c#

Related posts about LINQ