STRING.FORMAT WITH NULL VALUES C#

Total Post:135

Points:947
C# 
C#
 6019  View(s)
Ratings:
Rate this:

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?
  1. Post:412

    Points:2888
    Re: String.Format with null values C#

    Hi Chintoo,

    You 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.

      Modified On Apr-03-2018 06:23:43 AM

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!