Linq query with nullable sum(总和可为空的 Linq 查询)
问题描述
from i in Db.Items
select new VotedItem
{
ItemId = i.ItemId,
Points = (from v in Db.Votes
where b.ItemId == v.ItemId
select v.Points).Sum()
}
我收到了这个查询,但是如果没有发现异常投票,它就会失败:
I got this query, however it fails if no votes are found with exception:
The null value cannot be assigned to a member with type System.Int32 which is a non-nullable value type.
我假设它是因为 sum 返回一个 int 而不是一个可为空的 int,所以给 sum 一个 int?由于输入只给出相同的错误,可能导致 sum 仅适用于整数.
I assume its because sum returns an int and not a nullable int, giving sum a int? as input only give the same error, probably cause sum only workes on ints.
有什么好的解决方法吗?
Any good workaround for this?
推荐答案
from i in Db.Items
select new VotedItem
{
ItemId = i.ItemId,
Points = (from v in Db.Votes
where b.ItemId == v.ItemId
select v.Points ?? 0).Sum()
}
编辑 - 好吧,这个怎么样...(再次拍摄,因为我不知道你的型号...):
EDIT - ok what about this... (Shooting again since I don't know your model...):
from i in Db.Items
select new VotedItem
{
ItemId = i.ItemId,
Points = (from v in Db.Votes
where b.ItemId == v.ItemId)
.Sum(v => v.Points)
}
这篇关于总和可为空的 Linq 查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:总和可为空的 Linq 查询


基础教程推荐
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01