Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String.Format with null values C#

Tags:

c#

.net

c#-4.0

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?

like image 492
user2994641 Avatar asked May 10 '26 03:05

user2994641


1 Answers

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));
like image 130
McAden Avatar answered May 12 '26 17:05

McAden