2014-10-29 168 views
-2

處理空值我有一個LINQ聲明,看起來像這樣:與LINQ聲明

List<Product> products = Product.GetAll(); 
List<Department> departments = Deparment.GetAll(); 

var productList = (from product in products 
       select new 
       { 
       ProductId= product.ID, 
       ProductName = product.Name, 
       Departments = departments.Where(d => product.DepartmentIDs.Contains(d.Id)).ToList() 
       }); 

我的問題是,在product.DepartmentIDs字段可能爲空。這是由於最近的數據庫更改。此更改導致我的代碼中斷。如果product.DepartmentIDs不爲空,我如何更新檢索部門的Where子句以僅獲取部門? product.DepartmentIDs將是nullList<int>

+2

你應該在數據庫端而不是在內存中完成這項工作。 – Servy 2014-10-29 14:10:41

回答

4
departments.Where(d => 
     product.DepartmentIDs != null && product.DepartmentIDs.Contains(d.Id)).ToList()