I want to format an address. Here is my code:
address = String.Format("{0}, {1}, {2}, {3}, {4}, {5}, {6}",Unfortunately this produces 116 Knox St, , , , Watson, ACT, 2602 when Line2, Line3, Line4 are null. How can I handle the nulls to get a results like 116 Knox St, Watson, ACT, 2602?
postalAddress.Line1,
postalAddress.Line2,
postalAddress.Line3,
postalAddress.Line4,
postalAddress.Suburb,
postalAddress.StateCode,
postalAddress.Pcode);
Pravesh Singh
12-Dec-2013You can try this :
StringBuilder sb = new StringBuilder();
List<string> addressParts = new List<string> { postalAddress.Line1, postalAddress.Line2, postalAddress.Line3, postalAddress.Line4, postalAddress.Suburb, postalAddress.StateCode, postalAddress.Pcode };
addressParts.ForEach(x => sb.Append(String.IsNullOrEmpty(x) ? "" : ", " + x));
string address = sb.ToString().Trim(',');Hope this will solve your problem.