我有一个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
可以是null
或List<int>
。
答案 0 :(得分:4)
departments.Where(d =>
product.DepartmentIDs != null && product.DepartmentIDs.Contains(d.Id)).ToList()