在Linq中处理空值的最佳方法是什么。
我有这个代码从数据库中检索客户联系人,但如果联系人详细信息不存在,则会创建一个新实例
void SetProperty(int _CustomerID)
{
Contacts_GetResult Contact;
if (Global.VariableStore._Contact == null)
{
Contact = Cd.Contacts_Get(_CustomerID).SingleOrDefault();
if (Contact == null)
Contact = new Contacts_GetResult();
Global.VariableStore._Contact = Contact;
}
else
{
Contact = Global.VariableStore._Contact;
}
if (Contact != null)
{
HomeNumber.Value = Contact.HomeNumber.ToString();
MobileNumber.Value = Contact.MobileNumber.ToString();
WorkNumber.Value = Contact.WorkNumber.ToString();
EmailAddress.Value = Contact.EmailAddress.ToString();
}
当它创建新联系人时,所有值都为null,这使得下面的代码失败,因为值为null
HomeNumber.Value = Contact.HomeNumber.ToString();
我目前使用:
if (Contact.HomeNumber != null)
HomeNumber.Value = Contact.HomeNumber.ToString();
有更简单的方法吗?
答案 0 :(得分:2)
有很多方法,所有这些方法都包括检查空的方式:
if (Contact.HomeNumber != null)
HomeNumber.Value = Contact.HomeNumber.ToString();
HomeNumber.Value = (Contact.HomeNumber ?? string.Empty).ToString();
HomeNumber.Value = Contact.HomeNumber != null
? Contact.HomeNumber.ToString()
: string.Empty;
稍有不同的是,最后两个样本将用空字符串替换空值。在??
运算符的情况下,没有什么可以做的;整个代码构造是关于在操作之前确保该值不为null。该代码是其中最紧凑的代码,但在ToString
为HomeNumber
时,null
不必要的调用会带来缺点。
对于?:
运算符,可以轻松更改该示例以返回null而不是空字符串:
HomeNumber.Value = Contact.HomeNumber != null
? Contact.HomeNumber.ToString()
: null;
答案 1 :(得分:0)
我使用以下扩展方法(稍微)简化了对空实例的防护:
public static V ValueOrDefaultIfNull<T, V>(this T @this, Func<T, V> @value, V @default)
{
return @this != null ? @value(@this) : @default;
}
所以现在我可以这样打电话:
HomeNumber.Value = Contact.ValueOrDefaultIfNull(x => x.HomeNumber.ToString(), "N/A");