c# - LINQ .SUM() 和可为空的数据库值

标签 c# linq

我知道为什么会这样,但有人能指出正确的语法方向吗?

目前我有:

var expense = from e in db.I_ITEM
              where e.ExpenseId == expenseId
              select e;

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

我的问题是 x.Mileage 的类型是“double?”并且在数据库中有空值。

我得到的错误是:

Exception Details: System.InvalidOperationException: The cast to value type 'Double' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type.

正确的语法是什么?

最佳答案

令我惊讶的是它失败了,但是可能的另一种方法是简单地对可为 null 的值求和,然后然后使用 null 合并运算符:

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

当然,在 LINQ to Objects 中,如果序列中没有非空值,这会做正确的事情,忽略空值并为您提供空结果(在空合并运算符之前)。

关于c# - LINQ .SUM() 和可为空的数据库值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5154728/

相关文章:

javascript - MVC5 : Refresh View on button (hyperlink) click?

c# - .net 随机生成器是如何实现的?

vb.net - 你选择 Linq 而不是 For 循环?

c# - 林克错误 "Input string was not in a correct format."

Linq to Sql - 存储库模式 - 动态 OrderBy

linq - 如何使用 System.Linq.Dynamic 命名空间在 Dynamic Linq 中执行以下操作

c# - 为什么 0.ToString ("#.##") 返回一个空字符串而不是 0.00 或至少为 0?

c# - 在另一台计算机上远程连接到mysql时出现问题

c# - asp.net 以编程方式创建表和 css 优先级

entity-framework - 如何在 Linq 的 Where 条件中使用 IN 运算符