空检查在哪里?
Null check in where?
我有以下内容:
var tagId = "5288";
source.Where(p => p.GetPropertyValue<IEnumerable<string>>("picker").Contains(tagId));
这个returns错误System.ArgumentNullException: Value cannot be null.
所以有些返回的结果,不包含picker值。在上面的语句中,我将如何检查?
它是一个 Umbraco Multinode treepicker,它是 "picker" 值。
如果我没理解错的话,如果没有找到picker
值,GetPropertyValue
的结果可以是null
。在这种情况下,您可以使用 null conditional operator:
source.Where(p => p.GetPropertyValue<IEnumerable<string>>("picker")?.Contains(tagId) == true);
注意 GetPropertyValue
之后的 ?.
。如果该方法 returns null
则它不是 true
,因此那些将不会包含在过滤的对象中。
使用这个:
source.Where(p =>
{
var pickerVal = p.GetPropertyValue<IEnumerable<string>>("picker");
if (pickerVal == null)
return false;
return pickerVal.Contains(tagId);
});
或更浓缩:
source.Where(p =>
{
var pickerVal = p.GetPropertyValue<IEnumerable<string>>("picker");
return (pickerVal != null) && pickerVal.Contains(tagId);
});
我有以下内容:
var tagId = "5288";
source.Where(p => p.GetPropertyValue<IEnumerable<string>>("picker").Contains(tagId));
这个returns错误System.ArgumentNullException: Value cannot be null.
所以有些返回的结果,不包含picker值。在上面的语句中,我将如何检查?
它是一个 Umbraco Multinode treepicker,它是 "picker" 值。
如果我没理解错的话,如果没有找到picker
值,GetPropertyValue
的结果可以是null
。在这种情况下,您可以使用 null conditional operator:
source.Where(p => p.GetPropertyValue<IEnumerable<string>>("picker")?.Contains(tagId) == true);
注意 GetPropertyValue
之后的 ?.
。如果该方法 returns null
则它不是 true
,因此那些将不会包含在过滤的对象中。
使用这个:
source.Where(p =>
{
var pickerVal = p.GetPropertyValue<IEnumerable<string>>("picker");
if (pickerVal == null)
return false;
return pickerVal.Contains(tagId);
});
或更浓缩:
source.Where(p =>
{
var pickerVal = p.GetPropertyValue<IEnumerable<string>>("picker");
return (pickerVal != null) && pickerVal.Contains(tagId);
});