LINQ .SUM() and nullable db values

What about excluding the nulls, ie

var expense = 
          from e in db.I_ITEM
          where (e.ExpenseId == expenseId) && (e.Mileage.HasValue)
          select e;

 return expense.Sum(x => x.Mileage);

I'm surprised that fails, but an alternative which might work is simply to sum the nullable values and then use the null coalescing operator:

return expense.Sum(x => x.Mileage) ?? 0d;

Certainly in LINQ to Objects this would do the right thing, ignoring null values and giving you a null result (before the null coalescing operator) if there were no non-null values in the sequence.


may give you an opinion...

    decimal depts = 0;

    var query = from p in dc.Payments
                where p.UserID == UserID
                select p.Amount;

    if (query.Count() > 0)
    {
        depts = query.Sum();
    }

    return depts;

Tags:

C#

Linq