我有一个奇怪的 linq 子查询问题。
给定以下数据结构:
Parents Children ------- -------- Id Id ParentId Location HasFoo
(obviously this is not the real structure, but it's close enough for this example)
I'm able to run this query and get a desired result:
bool b = (from p in Parents
from c in Children
where p.Id == 1 && c.ParentId == p.Id && c.Location == "Home"
select c.HasFoo).SingleOrDefault();
因此,如果有一个 child 的位置为 Id 1 的父级的“家”,我将获得该 child 的“HasFoo”值,否则,我将获得 false,这是 bool 的“默认”值。
但是,如果我尝试编写查询,则我有一个 Parent 对象列表,如下所示:
var parentList = from p in Parents
select new ParentObject
{
ParentId = p.ParentId,
HasHomeChildren = p.Children.Count(c => c.Location == "Home") > 0,
HasHomeChildrenWithFoo = (from c in p.Children where c.Location == "Home" select c.HasFoo).SingleOrDefault()
}
遍历列表时出现以下错误:
不能将空值分配给 System.Boolean 类型的成员,该成员是不可为空的值类型。
但是,我看不到这个“空”值的来源。
最佳答案
我想知道编译器是否将 HasHomeChildrenWithFoo 推断为 bool,但实际上转换为可空的 bool(从而弄乱了您的 SingleOrDefault 调用)。无论如何,我愿意打赌您可以在最终选择中通过强制转换为可空类型来修复它,然后您可以在为空时手动默认为 false。它可能会使错误消失,但这是一种蛮力的混搭。
var parentList = from p in Parents
select new ParentObject
{
ParentId = p.ParentId,
HasHomeChildren = p.Children.Any(c => c.Location == "Home"),
HasHomeChildrenWithFoo = (from c in p.Children where c.Location == "Home" select (bool?)c.HasFoo) ?? false)
}
关于linq 子查询返回空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1089427/