gpt4 book ai didi

c# - 在 LINQ 中使用 SUM() 时排除 NULL 值

转载 作者:太空宇宙 更新时间:2023-11-03 13:18:14 27 4
gpt4 key购买 nike

我正在尝试使用 SUM() 来计算列中所有条目的总和,然后将数字转换为 int

我在转换过程中遇到了问题,因为有些条目是 NULL。我试图在 WHERE() 子句中使用 != null 排除它们,但我仍然遇到相同的错误

The cast to value type Int32 failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type.

这是我的 LINQ 查询,有人可以指出我遗漏的内容以正确排除空值吗?

TotalLiftings = db.Query<Transaction>().
Where(tr => tr.TerminalId == TerminalUserData.ID &&
tr.ProductId == t.ProductId &&
tr.TransactionDate == t.InventoryDate &&
tr.NetGallons != null).
Select(tr => tr.NetGallons).
Sum();

最佳答案

您只需转换为nullable int。发生错误是因为您尝试对没有记录求和,结果为 null,但 int 不能为 null

.Select(tr => tr.NetGallons).Cast<int?>().Sum(),

  .Select(tr => (int?)tr.NetGallons).Sum(),

关于c# - 在 LINQ 中使用 SUM() 时排除 NULL 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25289732/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com