【发布时间】:2021-01-12 16:52:04
【问题描述】:
我的应用程序中有一个地址模型:
**[Key]**
public int CustomerAddressId { get; set; }
public string CompanyName { get; set; }
public string Address1 { get; set; } **NOT NULL**
public string Address2 { get; set; }
public string Address3 { get; set; }
public string City { get; set; }
public string County { get; set; }
public string Postcode { get; set; } **NOT NULL**
**[ForeignKey]**
public int CountryId { get; set; }
我有一个 CountryId 为 CountryNameCustomer 的 Country 模型
我想在我的客户地址模型中添加一个计算字段,该模型输出单个地址行,同时考虑到任何可能为 NULL 的字段。
例如,对于以下地址:
地址 1: 4 雷蒙德街
地址 2:莱顿
城市:伦敦
邮编:W13 5TY
我希望我的计算域是“4 Raymond Road, Leyton, London, W13 5TY”。
我不确定实现这一目标的最优雅方式。
我可以这样做:
var address = "";
if(CompanyName != null){address += CompanyName + ",";}
if(Address1 != null){address += Address1 + ",";}
等等……
有没有更优雅的方法来实现这一点?
一切顺利。
【问题讨论】:
-
您可以尝试使用插值字符串,它可能会使代码更紧凑,但您编写的方式清晰易读。 docs.microsoft.com/en-us/dotnet/csharp/language-reference/…