格式化地址的不同部分

时间:2013-11-22 22:43:29

标签: c#

生成一行显示地址的字符串有什么好方法? 假设我在不同的变量中有Zip, State, Line1, Line2这样的地址部分。 我想生成像

这样的东西
Line1, Line2, City, State, Zip

请注意,某些字段可能会丢失。

简单而又丑陋的解决方案是检查这些值是否为空并决定是否添加“,”之间或不是,但就像我说我希望“更好”的方式?解析器或字符串格式化器可能吗?

3 个答案:

答案 0 :(得分:5)

创建这些值的临时数组,并仅将string.Join用于有效元素:

var str = string.Join(", ", new string[] { Line1, Line2, City, State, Zip }
                                .Where(s => !string.IsNullOrEmpty(s)));

答案 1 :(得分:1)

以下应该这样做。

String s = String.Format(" {0}, {1}, {2}, {3}, {4}", Line1, Line2, City, State, Zip).Replace(" ,", String.Empty);
if (s.EndsWith(",")) {
  s=s.SubString(0,s.Length-1);
}

答案 2 :(得分:1)

如果您希望您的字符串更具可读性(例如,如果您记录它),我建议您指出数据不可用而不是跳过它。此外,您可以将其包装在一个类中,以使其更易于维护。

public class Address
{
    private const string UnknownMessage = "Unknown";
    private const string AddressStringFormat = 
       "Addres Line 1: {0}, Address Line 2: {1}, City: {2}, State: {3}, Zip: {4}";

    public string AddressLine1 { get; set; }
    public string AddressLine2 { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string Zip { get; set; }

    public Address(string addressLine1, string addressLine2, string city, string state, string zip)
    {
        this.AddressLine1 = addressLine1;
        this.AddressLine2 = addressLine2;
        this.City = city;
        this.State = state;
        this.Zip = zip;
    }

    public string GetStringRepresentation()
    {
        return String.Format(AddressStringFormat, 
            String.IsNullOrWhiteSpace(AddressLine1) ? UnknownMessage : AddressLine1,
            String.IsNullOrWhiteSpace(AddressLine2) ? UnknownMessage : AddressLine2,
            String.IsNullOrWhiteSpace(City) ? UnknownMessage : City,
            String.IsNullOrWhiteSpace(State) ? UnknownMessage : State,
            String.IsNullOrWhiteSpace(Zip) ? UnknownMessage : Zip);
    }
}