我的应用程序中有一个地址模型:
**[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
我想将一个计算字段添加到我的客户地址模型中,该模型输出单个地址行,并考虑到任何可能为空的字段。
例如,对于以下地址:
地址1:雷蒙街4号
地址2:雷顿
城市:伦敦
邮编: W13 5TY
我希望我的计算字段为"4 Raymond Road,Leyton,London,W13 5TY“。
我不确定实现这一点的最优雅的方法。
我可以做类似以下的事情:
var address = "";
if(CompanyName != null){address += CompanyName + ",";}
if(Address1 != null){address += Address1 + ",";}以此类推。
有没有更优雅的方式来实现这一点?
万事如意。
发布于 2021-04-04 19:46:29
在“自定义地址”类中覆盖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)));
}https://stackoverflow.com/questions/65688336
复制相似问题