是否有更简洁的方法来设置此匿名类属性?

时间:2010-11-09 12:32:49

标签: c# null-coalescing-operator

我正在返回匿名课程:

var clients = from c in this.ClientRepository.SearchClientByTerm(term, 10)
    select new
    {
       id = c.Id,
       line1 = c.Address.Line1 ?? "Unknown Information ..."
    };

问题是Address是可空的,这意味着如果它是null,它会爆炸成一百万个。

我能想到的最优雅的解决方案是......

    line1 = c.Address != null && c.Address.Line1 != null 
               ? c.Address.Line1 : "Unknown Information ..."

有更好的方法吗?我不喜欢失去使用null-coalescing运算符的能力,然后必须检查是否为null。

3 个答案:

答案 0 :(得分:1)

我能想到的唯一更清晰的方法是修改Address属性的getter以永远不返回null,或让构造函数始终初始化Address。否则你总是需要检查是否为空。

答案 1 :(得分:1)

我只能想到这个:

line1 = c.Address.HasValue ?  c.Address.Line1.HasValue ? c.Address.Line1 : "Line1 unknown." : "Address unknown."

你也可以修改你的Address属性get {}方法来检查内容并返回适当的值,最好是缓存结果,这样它就不会反复进行相同的检查。

答案 2 :(得分:0)

我会ClientRepository.SearchClientByTerm()返回初始化的Address和(可能)设置Line1

相关问题