开发者

Is there a cleaner way to set this anonymous class property?

I am开发者_StackOverflow中文版 returning an anonymous class:

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

The problem is Address is nullable which means if it is null it explodes into a million pieces.

The most elegant solution i could think of was this...

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

Is there a better way?, i don't like losing the ability to use the null-coalescing operator and then having to check if null.


The only cleaner way I can think of is to modify the getter of the Address property to never return null, or have the constructor always initialize the Address. Otherwise you always need to check for null.


I could only think of this:

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

You could also modify your Address property get{} method to check for contents and return appropriate value, preferably cache the results so it doesn't run the same check over and over.


I would have ClientRepository.SearchClientByTerm() return an initialized Address and (possibly) set Line1 there.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜