I'd recommend McAden solution, it's elegant and solves your problem nicely. Stated below is one option on how to use the StringBuilder, it's very verbose compared to the others.
As stated in the comments you can use the StringBuilder and a series of if statements. Thsi code can be cleaned up nicely but to let you play with it and understand what is going on, here is an example:
var postalAddress = new {
Line1 = "116 Knox St",
Line2 = "",
Line3 = "",
Line4 = "",
Suburb = "Watson",
StateCode = "ACT",
Pcode = "2602",
};
var builder = new StringBuilder();
builder.AppendFormat("{0}, ", postalAddress.Line1);
if(!string.IsNullOrEmpty(postalAddress.Line2))
{
builder.AppendFormat("{0}, ", postalAddress.Line2);
}
if(!string.IsNullOrEmpty(postalAddress.Line3))
{
builder.AppendFormat("{0}, ", postalAddress.Line3);
}
if(!string.IsNullOrEmpty(postalAddress.Line4))
{
builder.AppendFormat("{0}, ", postalAddress.Line4);
}
builder.AppendFormat("{0}, ", postalAddress.Suburb);
builder.AppendFormat("{0}, ", postalAddress.StateCode);
builder.AppendFormat("{0}", postalAddress.Pcode);
var result = builder.ToString();
When you print the result variable you will now have the following result:
116 Knox St, Watson, ACT, 2602
Basically you can use AppendFormat to append the string in a formatted manner and you can experiment and play around with this until it behaves as you like, then you can refactor it to be a bunch less lines thane this!
StringBuilder+if?StringBuilderis? How aboutif?