4
我有一個奇怪的LINQ子查詢問題。LINQ子查詢返回null
由於數據結構如下:
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」值,否則,我會得到錯誤的,這是我s是bool的「默認」值。
不過,如果我嘗試編寫查詢,所以我的父對象列表,像這樣:
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.
但是,我沒有看到這個「空值」來自哪裏。
似乎很奇怪必須這樣做,但它的工作原理!謝謝! :) – Jonas 2009-07-06 22:33:58