2017-04-20 52 views
1

我在C#中創建簡單網絡表單。在這裏,我通過串聯的方式獲得完整的地址,這很有效。但是,讓我們假設如果我沒有address2,city等,那麼我想跳過在每個字符串末尾附加逗號(例如,如果address1爲空或空)。僅在字符串不爲空或空時附加逗號

string address1 = "Address1"; 
string address2 = "Address2"; 
string city = "City"; 
string country = "Country"; 
string postalCode = "00000"; 

string fullAddress = ? --> address1 + ","+ address2 +","+ city and so on 

回答

11

如果你想刪除空或空字符串,你必須在連接方法中使用的濾鏡陣列:如果我們做city=""

var array = new[] { address1, address2, city, country, postalCode }; 
string fullAddress = string.Join(",", array.Where(s => !string.IsNullOrEmpty(s))); 

我們有Address1,Address2,Country,00000

+0

太棒了!這工作 – sgl

0

你可以把你所有的元素放在一個數組中,並用「,」加入數組。在這種情況下,逗號將位於不同的地址部分之間。

+0

你能告訴我代碼 – sgl

3

您可以使用string.join以及filter在一個或多個值爲空或空白時刪除重複的逗號。

Console.WriteLine(string.Join(",", new string[] { address1 , address2 , city , country , postalCode }.Where(c => !string.IsNullOrEmpty(c)))); 
+0

這doe當其中一個值爲空時,不會刪除重複的逗號 –

+0

@RufusL將更新我的答案以適應此情況。 –

2

您可以使用string.Join來完成您的任務。你可以run in dotnetfiddle。 請檢查下面的代碼:

using System; 
using System.Collections.Generic; 
using System.Linq; 

public class Program 
{ 
    public static void Main() 
    { 
     string address1 = "Address1"; 
     string address2 = "Address2"; 
     string city = "City"; 
     string country = "Country"; 
     string postalCode = "00000"; 

     List<string> strArray = new List<string> { address1, address2, city, country, postalCode }; 

     string fullAddress = string.Join(",", strArray.Where(m=> !string.IsNullOrEmpty(m)).ToList()); 

     Console.WriteLine(fullAddress); 
    } 
} 
+0

我已經更新了我的答案,它將忽略「空」值。 – csharpbd

+0

我更新了[fiddle輸出](https://dotnetfiddle.net/2hJpHi)。 – csharpbd

0

String.Join是你所需要的。

string address1 = "Address1"; 
string address2 = "Address2"; 
string city = "City"; 
string country = "Country"; 
string postalCode = "00000"; 

string[] stuff = new string [] { address1, address2, city, country, postalCode }; 

string fulladdress = string.Join(",", stuff).Replace(",,",","); 
+0

你的答案沒有解決空變量問題。 – Rafael

+0

當其中一個值爲空時,不會刪除重複的逗號 –

+0

這是因爲字符串是可爲空的類型。 'string.Join'用假定其他代碼正在確定空處理的情況下用「string.Empty」代替空參數值。如果數組本身爲空,則拋出異常。我建議作爲一個問題分離的問題,跟在'string.Replace()'用「,」替換「,,」將更好地解決空值。我用這個更新了答案。 – CDove

2

試試這個:

string address1 = "Address1"; 
string address2 = "Address2"; 
string city = ""; 
string country = "Country"; 
string postalCode = "00000"; 

Func<string, string> f = s => string.IsNullOrEmpty(s) ? string.Empty : string.Format("{0},", s); 
string fullAddress = string.Format("{0}{1}{2}{3}{4}", f(address1), f(address2), f(city), f(country), f(postalCode)).Trim(','); 
+1

這是正確的答案。它說明變量爲空。 – Rafael

相關問題