在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();有没有更简单的方法?
发布于 2010-09-03 17:30:06
有许多方法,所有这些方法都包括以某种方式检查null:
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;最后两个示例会用空字符串替换空值,这一点略有不同。对于??运算符,对此没有什么可做的;整个代码构造都是为了确保在对其进行操作之前值不为空。这些代码是其中最紧凑的,但当HomeNumber为null时,会带来不必要的ToString调用的缺点。
在使用?:运算符的情况下,可以很容易地将该示例更改为返回null而不是空字符串:
HomeNumber.Value = Contact.HomeNumber != null
? Contact.HomeNumber.ToString()
: null;发布于 2010-09-03 18:05:44
我使用以下扩展方法来(在某种程度上)简化对空实例的防范:
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");https://stackoverflow.com/questions/3634471
复制相似问题