2009-07-06 303 views
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.

但是,我沒有看到這個「空值」來自哪裏。

回答

2

我不知道編譯器是否推斷HasHomeChildrenWithFoo是布爾,但實際上是鑄造爲一個可空布爾(因此弄亂了你的SingleOrDefault調用)。無論如何,我願意打賭你可以通過在最終選擇中將其轉換爲可空類型來修復它,然後可以在null時手動將其默認爲false。它可能會使錯誤消失,但它是一種蠻力kludge。

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) 
       } 
+0

似乎很奇怪必須這樣做,但它的工作原理!謝謝! :) – Jonas 2009-07-06 22:33:58