【发布时间】:2016-07-13 23:22:04
【问题描述】:
我有一个类来描述存储的各种电话。有时Importance 属性可以为空。这里是课堂
public class PhoneTypeListInfo
{
public string AccountNum { get; set; }
public int PhoneType { get; set; }
public string PhoneNum { get; set; }
public int Importance { get; set; }
}
我定义了一个函数,如果电话号码和帐号与给定的一组值匹配,它将返回 PhoneTypeListInfo。
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 获取“Importance”属性。
我的问题最终是,我需要做什么才能让p.Importance 为空,如果它为空,则将其设置为 0,使 x.Importance 也为 0。
【问题讨论】:
-
我不认为
p.Importannce为空,而是p本身。 -
我认为 Scott 是对的,您需要对 p 本身进行额外检查,因为
RetrievePhoneType可以返回null -
空传播操作符 ?。在这里可能有用。
-
因为重要性不是可以为空的 int 这个表达式:
(p.Importance as int?).HasValue始终为真