2015-05-20 17 views
3

我正在使用動態LINQ(System.Linq.Dynamic)(你可能在這裏找到描述,http://dynamiclinq.azurewebsites.net/GettingStarted)。在System.Linq.Dynamic.Select()中,如何以簡單的方式處理空對象引用?

下面的語句適用

Products.Select("new(ProductName, CategoryID.CategoryName as CategoryName)"); 

但我無意中發現,當類別ID爲空,結果是空的。但我認爲它會返回如下記錄:

ProductName =「Wine」,CategoryName =「」(或null)。

然後我找到了一種方法來做到這一點通過

Products.Select("new(ProductName, iif(CategoryID==null,\"\",CategoryID.CategoryName) as CategoryName)"); 

聲明是醜陋的。

你有更好的解決方案嗎?

謝謝你在前進,

+1

「new(ProductName,CategoryID == null?null:CategoryID.CategoryName)as CategoryName)」working。正如Cory提到的那樣,使用null似乎更簡單一些。 – Ying

+0

更難看的示例是:grand == null?null:(grand.parent == null?null:grand.parent.son)。 – Ying

回答

3

我發現的唯一的事情是here。目前還不清楚爲什麼該解決方案被接受,但我沒看到有,你可以這樣做:

"new(ProductName, iif(CategoryID==null,null,CategoryID.CategoryName) as CategoryName)" 

,而不是這樣的:

"new(ProductName, iif(CategoryID==null,\"\",CategoryID.CategoryName) as CategoryName)" 

這不是任何短,但對我來說,它使代碼更具可讀性,因爲您只是使用null而不是轉義引號。

+0

「new(ProductName,CategoryID == null?null:CategoryID.CategoryName)as CategoryName)」 – Ying

相關問題