题
我具有奇数LINQ子查询的问题。
鉴于如下的数据结构:
Parents Children ------- -------- Id Id ParentId Location HasFoo
(显然这不是真正的结构,但它是足够接近这个例子)
我能够运行这个查询,并得到想要的结果:
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();
所以,如果有是有编号1的父位置“首页”孩子,我会得到孩子的“HasFoo”值,否则,我会得到错误的,这是“默认”值了布尔。
不过,如果我尝试编写查询,所以我的父对象列表,像这样:
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()
}
遍历列表时我得到以下错误:
The null value cannot be assigned to a member with type System.Boolean which is a non-nullable value type.
我看不出这种“空”值从然而到来,
解决方案
我不知道如果编译器推断HasHomeChildrenWithFoo是布尔,但后来实际上铸造一个可空布尔(从而搞乱你的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)
}
不隶属于 StackOverflow