I want to format an address. Here is my code:
address = String.Format("{0}, {1}, {2}, {3}, {4}, {5}, {6}",
postalAddress.Line1,
postalAddress.Line2,
postalAddress.Line3,
postalAddress.Line4,
postalAddress.Suburb,
postalAddress.StateCode,
postalAddress.Pcode);
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?
Looks like this accomplishes your purpose much more concisely.
string[] data = new[] {
postalAddress.Line1,
postalAddress.Line2,
postalAddress.Line3,
postalAddress.Line4,
postalAddress.Suburb,
postalAddress.StateCode,
postalAddress.Pcode
};
string address = string.Join(", ",
data.Where(e => !string.IsNullOrWhiteSpace(e));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With