Alex Rivera | Logout

Sum() causes exception instead of returning 0 when no rows

Asked 2009-02-23T09:16:23.923
18

I have this code (ok, I don't, but something similar :p)

    var dogs = Dogs.Select(ø => new Row
    {
            Name = ø.Name,
            WeightOfNiceCats = ø.Owner
              .Cats
              .Where(æ => !æ.Annoying)
              .Sum(æ => æ.Weight),
    });

Here I go through all dogs and sum up the weight (into a non-nullable decimal) of all not-annoying cats which has the same owner as the dog. Of course, pretty much all cats are annoying, so I get this error:

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

None of the fields or foreign keys used can be null. So the error happens when the Where clause returns no cats, which it often does. But how can I solve this? I want it to return 0 when that happens. Tried with a DefaultIfEmpty() after the Where clause, but then I get this error:

Object reference not set to an instance of an object.

Which I guess is understandable. I tried to add a ?? after the Sum, but then it wont compile because of this error:

Operator '??' cannot be applied to operands of type 'decimal' and 'decimal'

Which also makes sense of course. So what can I do? Would be nice if the Sum thing just returned 0 when there was nothing to sum. Or a SumOrZero statement of some sort. Would it be difficult to make a SumOrZero method that worked with Linq2SQL?

Edit
Report

1 Answer

0

You want to use DefaultIfEmpty, which will return an IEnumberable with a single element of 0, and that will be semantically the same as you require.

As you have a nullable decimal, you will probably have to use the 2nd version of the method taking 2 parameters.

answered 2009-02-23T09:37:32.950

Your Answer