使用 Any() 关键字对反射的 属性 的值进行空检查

Null check for reflected property's value with Any() keyword

我有一个 Entity Framework DAL 对象列表,我在其中使用可以包含逗号的 查询参数字符串 。我正在尝试从 DAL 列表中获取满足查询参数字符串中的值的所有对象。

我有以下 Linq 语句产生了我所期望的结果:

dalList = dalList
   .Where(aa => queryParamString.Split(',')
      .Any((x => (aa.GetType().GetProperty(kvp.Key).GetValue(aa, null)).ToString().ToLower() == x.ToLower())))
   .ToList();

以上语句工作正常如果列表不包含反射的空值 属性。

如何在此 Linq 语句中包含 null 检查以避免在第一次 ToString() 方法调用时出现 NullReferenceException?

编辑:kvp.Key 是数据库列的字符串表示形式

A null-conditional operator ?. 可用于使空检查更简洁并避免空引用异常。

来自 MSDN a?.x 被评估为:

  • If a evaluates to null, the result of a?.x ... is null.
  • If a evaluates to non-null, the result of a?.x ... is the same as the result of a.x ...

所以因为 .GetValue(aa, null) 可以 return null,为了避免在 null 上调用 ToString() 时出现空引用异常,我们可以使用 .GetValue(aa, null)?.ToString() ,在空值的情况下只是 returns null without NRE.

那么即使?.运算符是短路运算符,ToString()一般也可以returnnull,所以最好再次使用null条件运算符ToString()?.ToLower()。变成:

GetValue(aa, null)?.ToString()?.ToLower() == x.ToLower()

==(此处为 string equality operator)允许 null 作为参数,因此我们可以避免空引用异常。