我的应用程序中有一个地址模型:
**[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,CountryName客户的国家/地区型号
我想在我的客户地址模型中添加一个计算字段,该字段输出单个地址行,并考虑任何可能为NULL的字段。
例如,对于以下地址:
地址1:4 Raymond Street
地址2:Leyton
城市:伦敦
邮编:W13 5TY
我希望我的计算字段是";4 Raymond Road,Leyton,London,W13 5TY";。
我不确定实现这一点的最优雅的方式。
我可以做以下事情:
var address = "";
if(CompanyName != null){address += CompanyName + ",";}
if(Address1 != null){address += Address1 + ",";}
等等…
有没有更优雅的方式来实现这一点?
一切顺利。
在"自定义地址"类中覆盖ToString
,如下所示:
public override string ToString()
{
var parts = new List<string>();
parts.AddRange(new [] {CompanyName, Address1, Address2, Address3, City, County, Postcode});
return string.Join(", ", parts.Where(part => !string.IsNullOrEmpty(part)));
}