Search code examples
c#stringstring.formatpostal-code

Format address string - postal code and flat number


I need to format addres in one string. Now I have properties like:

public string Street { get; set; }
public string StreetNumber { get; set; }
public string FlatNumber { get; set; }
public string PostalCode { get; set; }
public string City { get; set; }

Now I have

String.Format("{0} {1} / {2} {3} {4}", model.Address.Street, model.Address.StreetNumber, model.Address.FlatNumber, data.Address.PostalCode, data.Address.City);
  1. Postal code is in format "xxxxx" (x is number). I want have postal code in format "xx-xxx".
  2. There is no always Flat number, so how can I hide flat number and character '/' if flat number is empty string ?

Solution

  • You can do this:

    String.Format("{0} {1} {2} {3}-{4} {5}", 
        model.Address.Street, 
        model.Address.StreetNumber, 
        (!string.IsNullOrEmpty(model.Address.FlatNumber ? '/ ' + model.Address.FlatNumber : ""), 
        data.Address.PostalCode.Substring(0, 2), 
        data.Address.PostalCode.Substring(2), 
        data.Address.City);
    

    A couple of things to point out:

    1. I removed the slash / from your format string and added a statement using a ternary operator

      (!string.IsNullOrEmpty(model.Address.FlatNumber ? "/ " + model.Address.FlatNumber : "")

    This will check if the FlatNumber is null and, if not, use / followed by the FlatNumber or, if so, use just an empty string.

    1. I added an additional index to your format, i.e. {3}-{4}, for the postal code. Then the associated statements will extract portions of the postal code to go before and after the dash -:

      data.Address.PostalCode.Substring(0, 2) //before the dash data.Address.PostalCode.Substring(2) //after the dash