gpt4 book ai didi

c# - 在 LINQ 求和表达式中处理 null

转载 作者:太空狗 更新时间:2023-10-29 22:21:28 25 4
gpt4 key购买 nike

我正在使用 LINQ 查询来查找列的总和,在少数情况下该值有可能为 null

我现在使用的查询是

int score = dbContext.domainmaps.Where(p => p.SchoolId == schoolid).Sum(v => v.domainstatement.Score ?? 0);

其中domainstatement可以为null,score也可以为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.

那么如何有效地处理 null 异常并将 sum 作为 INT 值返回呢?

最佳答案

这里

Sum(v => v.domainstatement.Score ?? 0);

您刚刚将空合并运算符放在了错误的位置。通常这样的错误是通过将不可空类型提升为可空类型来解决的(不需要 DefaultOrEmpty 和空检查),但是这里你已经有了一个可空类型,并且使用空合并运算符你做了相反的事情错误消息告诉您什么 - 查询必须使用可为 null 的类型

只需将它移动到之后 Sum 调用,问题就消失了:

Sum(v => v.domainstatement.Score) ?? 0;

关于c# - 在 LINQ 求和表达式中处理 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43766904/

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