2016-07-13 50 views
2

我有一個類描述存儲的各種電話。有時Importance屬性可以爲空。這裏是我已經定義了將返回PhoneTypeListInfo如果電話號碼和賬戶號碼匹配一組給定值的函數的類可空類型和.HasValue仍然會拋出一個空異常

public class PhoneTypeListInfo 
{ 
    public string AccountNum { get; set; } 
    public int PhoneType { get; set; } 
    public string PhoneNum { get; set; } 

    public int Importance { get; set; } 
} 

protected PhoneTypeListInfo RetrievePhoneType(string info, string acctNumber) 
    { 
     PhoneTypeListInfo type = xPhoneTypeList.Where(p => p.PhoneNum == info && p.AccountNum == acctNumber).FirstOrDefault(); 

     return type; 
    } 

這一切都很好。我遇到的問題是下面的linq查詢。

List<AlertBasedPhones> xAccountPhones = new List<AlertBasedPhones>(); 
xAccountPhones = (from x in xAccountStuff 
        where x.Media == "Phone" 
        let p = RetrievePhoneType(x.Info, acct.AccountNumber) 
        let xyz = x.Importance = (p.Importance as int?).HasValue ? p.Importance : 0 
        orderby p.Importance descending 
        select x).ToList(); 

什麼我上面做的是試圖使用具有不同組成的不同的類,除獲得來自PhoneTypeListInfo的「重要性」屬性。

我的問題最終是,我需要做什麼才能讓p.Importance爲空,如果它爲空則將其設置爲0,同樣使得x.Importance也爲0。

+2

我不認爲它是'p.Importannce'是空的,但'p'本身。 –

+0

我認爲Scott是對的,因爲'RetrievePhoneType'可以返回null null' –

+0

null progagating operator ?,所以您需要額外檢查p本身。在這裏可能很有用。 –

回答

6

這不是p.Importannce即爲空,而是本身。這是你需要首先檢查null的東西。如果您正在使用C#6,則可以使用?.運算符。您也可以將(p.Importance as int?).HasValue ? p.Importance : 0的邏輯抹平爲p.Importance ?? 0。結合兩者你得到

List<AlertBasedPhones> xAccountPhones = new List<AlertBasedPhones>(); 
xAccountPhones = (from x in xAccountStuff 
         where x.Media == "Phone" 
         let p = RetrievePhoneType(x.Info, acct.AccountNumber) 
         let xyz = x.Importance = p?.Importance ?? 0 
         orderby p?.Importance descending 
         select x).ToList(); 
+0

p不爲空。我會測試羅伯茨的答案,但看起來我應該用三元組代替。 –

+0

@ChrisClark如果0行匹配'xPhoneTypeList.Where(p => p.PhoneNum == info && p.AccountNum == acctNumber)',那麼'p'將爲空。 Robert的答案是使用'(null == p)'進行相同的空檢查,我只是使用了C#6中引入的更簡便的'。.'運算符。 –

+0

@ChrisClark如果您確信自己永遠不會遇到這樣的情況'xPhoneTypeList.Where(p => p.PhoneNum == info && p.AccountNum == acctNumber)'返回0行,然後將'.FirstOrDefault()'改爲'.First()',這樣就會拋出異常有0行(但如果沒有0行它不會是一個問題) –

2

使用三元運算符。將p.Importance替換爲(null==p) ? 0 : p.Importance