c# - 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'
解决方案
原因是字符串连接是在三元表达式之前完成的。
基本上你在做什么是这样的:
(v.....Address1.ToLower() + ", " + v.....Address2) == null
? ""
:v.Property.MailingAddress.Address2.ToLower()
由于表达式不为空,它会尝试获取 Address2,然后崩溃。
解决方案是在三元表达式周围添加括号:
... + (v.....Address2 == null ? "" : v.....Address2.ToLower())
这会将三元表达式与字符串连接隔离开来。
推荐阅读
- c++ - 在 C++ 中转换为 UTC 时区使时间保持不变(无论原始时区如何)
- r - 如何按组应用 auto.arima?
- mysql - mysql在列表中添加约束检查列
- python - 如何转换和组合两个 DataFrame
- javascript - 解决在 useEffect 中使用自定义挂钩?
- python - 如何通过 python API 下载历史 Azure ML 实验运行的输出
- r - 图表条仅在 ggplot 中 y 轴的下限设置为 0 时出现
- git - git 恢复到有冲突的特定提交
- excel - 如何将我的 FILTER() 公式替换为以前版本的 Excel?
- reactjs - 如何将任意字符串 HTML 内容注入 gatsbyjs 网站的头部?