2013-12-12 59 views
2

我想格式化地址。這裏是我的代碼:具有空值的String.Format C#

address = String.Format("{0}, {1}, {2}, {3}, {4}, {5}, {6}", 
         postalAddress.Line1, 
         postalAddress.Line2, 
         postalAddress.Line3, 
         postalAddress.Line4, 
         postalAddress.Suburb, 
         postalAddress.StateCode, 
         postalAddress.Pcode); 

很不幸,這會產生116 Knox St, , , , Watson, ACT, 2602當2號線,3號線,線路4是空的。我如何處理空值以得到如116 Knox St, Watson, ACT, 2602的結果?

+1

'StringBuilder' +'if'? – zerkms

+0

請你詳細說明一下嗎? – user2994641

+5

你知道'StringBuilder'是什麼嗎? 「if」怎麼樣? – zerkms

回答

12

看起來像這樣可以更簡潔地完成您的目的。

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)); 
1

在這裏,你去。這不會是非常有效的,但應該工作;)

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(','); 
1

我建議McAden解決方案,它的優雅和很好解決您的問題。下面是關於如何使用StringBuilder的一個選項,它與其他的比較非常詳細。

如評論中所述,您可以使用StringBuilder和一系列if語句。 Thsi代碼可以很好地清理而是讓你玩它,瞭解正在發生的事情,這裏有一個例子:

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(); 

當您打印result變量,你現在有以下結果:

116 Knox St, Watson, ACT, 2602

基本上你可以使用AppendFormat字符串中追加一個格式化的方式,你可以嘗試和玩,直到它的行爲,只要你喜歡,那麼你可以重構它是領主這一堆不太行!

0

怎麼樣一個單線程正則表達式來刪除重複和空格。

address = String.Format("{0}, {1}, {2}, {3}, {4}, {5}, {6}", 
         postalAddress.Line1, 
         postalAddress.Line2, 
         postalAddress.Line3, 
         postalAddress.Line4, 
         postalAddress.Suburb, 
         postalAddress.StateCode, 
         postalAddress.Pcode); 

address = Regex.Replace(address, @"(,\s)+", @"$1");