【问题标题】:LINQ equivalent of SQL IsNull(..,..) in the Where ClauseLINQ 等效于 Where 子句中的 SQL IsNull(..,..)
【发布时间】: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 子句中有错字。

  1. 正如@JeffMercado 指出的那样,应该是t.price不是 ord.price
  2. 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

标签: c# linq


【解决方案1】:

你可以这样做:

Query1 = from c in Customers
             join ord in Orders on c.CustomerId equals ord.CustomerId into cord
               from t in cord.DefaultIfEmpty()
             where (ord.price ?? 0) > 100
             select new {CustName = c.Name, OrderID = (t == null ? 0 : t.OrderId)};

【讨论】:

  • 感谢您的帮助。使用您的建议,我收到错误 operator ?? cannot be applied to operands of type 'int' and 'int'。我不确定,但这可能与我帖子中的 Note 有关。
  • 那么 price 不能为空,它必须是 int 类型?
  • 是的,正如我在帖子中的 Note 中指出的那样。
  • 抱歉,帖子中有错字。我在帖子中添加了一个更新部分。
【解决方案2】:

你有语法问题:

where t.price = null || t.price > 100

应该是:

where t.price == null || t.price > 100

注意:==

发生的事情是您分配t.price = null,结果是null。 如此有效地解决了null || t.price > 100 这就是编译器给你的原因:

运算符 ||不能应用于“”和“int”类型的操作数

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-29
    相关资源
    最近更新 更多