2011-08-16 19 views
2

我使用這個代碼:我該如何解決這個LINQ函數?

  var nextLevel = (from p in cd.Objective 
          where p.Parent_ObjectiveID == null 
          select p.Level); 

而且它的工作原理,通過它沒有返回元素的瞬間(因爲我沒有在我的數據庫中的任何元素)。雖然我想知道頂級這樣做:

  var nextLevel = (from p in cd.Objective 
          where p.Parent_ObjectiveID == null 
          select p.Level).Max(); 

但我得到一個錯誤:

空值不能分配給具有類型System.Int32一個成員是一個非空的值類型。

Parent_ObjectiveID是一個可以爲null的int並且只能在int中使用。

回答

4

Max正在尋找返回int,因爲這是p.Level的類型,但被迫返回null(因爲查詢中沒有項目)。如果您將p.Level轉換爲可爲空的int,則您的查詢應該可以工作。

var nextLevel = (from p in cd.Objective 
       where p.Parent_ObjectiveID == null 
       select (int?)p.Level).Max(); 
+0

確切地說,那是有效的。感謝Jacob –

+0

好的交易。樂於幫助。 :) –