首页 > 解决方案 > lambda 表达式中的三元运算符不适用于空值

问题描述

我有以下查询:

x.Organization.ClientActivityLogs.OrderByDescending(c => c.ActivityDate).Select(v =>
          v.Property.MailingAddress.Address1.ToLower() + ", " +
          v.Property.MailingAddress.Address2 == null ? "" 
                      :v.Property.MailingAddress.Address2.ToLower()
        ).FirstOrDefault()

在另一个查询中使用时有效,但当 Adress2(string) 在查询外的对象上使用时给我以下错误:

 System.NullReferenceException: 'Object reference not set to an instance of an object.'
    
    Jobba.DataLayer.Address.Address2.get returned null.

我不太明白为什么会这样。

当我使用Address2.FirstOrDefault()错误更改为:

'Value cannot be null.
Parameter name: source'

标签: c#

解决方案


原因是字符串连接是在三元表达式之前完成的。

基本上你在做什么是这样的:

(v.....Address1.ToLower() + ", " + v.....Address2) == null
    ? "" 
    :v.Property.MailingAddress.Address2.ToLower()

由于表达式为空,它会尝试获取 Address2,然后崩溃。

解决方案是在三元表达式周围添加括号:

... + (v.....Address2 == null ? "" : v.....Address2.ToLower())

这会将三元表达式与字符串连接隔离开来。


推荐阅读