在LINQ语句中处理Null

时间:2014-10-29 13:51:22

标签: c# 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字段可能为空。这是由于最近的数据库更改。此更改导致我的代码中断。如果Where不为空,如何更新检索部门的product.DepartmentIDs子句以仅获取部门? product.DepartmentIDs可以是nullList<int>

1 个答案:

答案 0 :(得分:4)

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