【问题标题】:C# Address Model - Concatenate Address1, Address2 etc into a computed fieldC# 地址模型 - 将地址 1、地址 2 等连接到计算字段中
【发布时间】: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 + ",";}

等等……

有没有更优雅的方法来实现这一点?

一切顺利。

【问题讨论】:

标签: c# oop model


【解决方案1】:

在您的“自定义地址”类中覆盖 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)));
        }

【讨论】:

    猜你喜欢
    • 2012-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-21
    相关资源
    最近更新 更多