2010-09-03 105 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");