【发布时间】:2018-04-30 14:13:34
【问题描述】:
在下面的 OUTER JOIN LINQ 查询中,如果右侧行为空(如果 c.CustomerID 与外部联接中的 ord.CustomerID 不匹配),我将在 Where 子句中得到空异常。 问题:如果下面Where clause中的ord.price为空,我该如何处理注意:price是int?类型的可空列。
Query1 = from c in Customers
join ord in Orders on c.CustomerId equals ord.CustomerId into cord
from t in cord.DefaultIfEmpty()
where t.price = null || t.price > 100
select new {CustName = c.Name, OrderID = (t == null ? 0 : t.OrderId)};
更新:
很抱歉,where 子句中有错字。
- 正如@JeffMercado 指出的那样,应该是
t.price而不是ord.price -
Where子句中缺少一个子句。我已将其更正为:where t.price = null || t.price > 100。但现在我得到了错误:operator || cannot be applied to operands of type '<null>' and 'int'
【问题讨论】:
-
如果 price 可以为空,那么您可以在 where 子句中添加条件,即 where ord.price > 100 && ord.price != null
-
@RohitGarg 抱歉,帖子中有错字。我在帖子中添加了一个更新部分。
-
@RohitGarg 他必须把 ord.price != null 放在短路“AND”之前,像这样“ ord.price != null && ord.price > 100” 如果为 null 那么第二个条件不会被检查。 :)
-
变量
ord在这种情况下是不可访问的......你应该在到达 NRE 之前很久就遇到语法错误。 -
null检查应该类似于select:where t == null || t.price > 100