2010-09-03 106 views
0

在Linq中处理空值的最佳方法是什么?LINQ to SQL处理空值

我有这样的代码从数据库中检索客户的联系,但如果不存在的联络方式它会创建一个新的实例

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

HomeNumber.Value = Contact.HomeNumber.ToString(); 

我目前使用的:

if (Contact.HomeNumber != null) 
HomeNumber.Value = Contact.HomeNumber.ToString(); 

有没有更简单的方法?

回答

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。该代码是最紧凑的代码,但当HomeNumbernull时,不必要地拨打ToString

?:操作者的情况下,样品可以很容易地被改变,以空代替返回一个空字符串的:

HomeNumber.Value = Contact.HomeNumber != null 
         ? Contact.HomeNumber.ToString() 
         : null; 
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");