我有一個類描述存儲的各種電話。有時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。
我不認爲它是'p.Importannce'是空的,但'p'本身。 –
我認爲Scott是對的,因爲'RetrievePhoneType'可以返回null null' –
null progagating operator ?,所以您需要額外檢查p本身。在這裏可能很有用。 –