无论如何使用NULL合并运算符来简化此代码?

时间:2014-04-25 17:49:50

标签: c# null-coalescing-operator

我有这段代码:

Phone addrFax = address.Phones.Phone.SingleOrDefault(p => p.PhoneType == PhoneTypeEnum.Fax);
if (addrFax != null)
    tba.Fax = addrFax.PhoneNumber;

对于各种PhoneType值,它会重复多次。整件事情很丑陋 我一直在玩NULL合并运算符(??)尝试以下列方式简化代码,但它不起作用。

tab.Fax = address.Phones.Phone.SingleOrDefault(p => p.PhoneType == PhoneTypeEnum.Fax).PhoneNumber ?? "";

有没有办法将我所拥有的内容转换为更容易消化的单行内容?

3 个答案:

答案 0 :(得分:2)

不,你还不能这样做,但是C#6中会出现monadic null检查。然后你可以写

tab.Fax = address.Phones.Phone.SingleOrDefault(p => p.PhoneType == PhoneTypeEnum.Fax)?.PhoneNumber ?? "";

请注意?.之前的PhoneNumber

答案 1 :(得分:2)

以下情况如何?

tba.Fax = address.Phones.Phone.Where(p => p.PhoneType == PhoneTypeEnum.Fax)
                              .Select(p => p.Fax)
                              .SingleOrDefault() ?? string.Empty;

答案 2 :(得分:1)

    Phone addrFax = address.Phones.Phone.Any(p => p.PhoneType == PhoneTypeEnum.Fax) ?
address.Phones.Phone.Single(p => p.PhoneType == PhoneTypeEnum.Fax).PhoneNumber : string.empty

为什么不想定义单独的功能?

Phone addrFax = GetPhone(address.Phones.Phone, PhoneTypeEnum.Fax)

public string GetPhone(PhoneTypeEnum phontype, IEnumerable<Phone> phones)
{
   return phones.Any(p => p.PhoneType == phontype) ? phones.Single(p => p.PhoneType == phontype).PhoneNumber : string.Empty;
}