我在C#中创建简单的webform.在这里,我通过连接哪个效果很好来获得完整的地址.但是,让我们说,如果我没有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
Run Code Online (Sandbox Code Playgroud)
Ale*_*ria 45
如果要删除空字符串或空字符串,则必须过滤连接方法中使用的数组:
var array = new[] { address1, address2, city, country, postalCode };
string fullAddress = string.Join(",", array.Where(s => !string.IsNullOrEmpty(s)));
Run Code Online (Sandbox Code Playgroud)
如果我们做到city=""了Address1,Address2,Country,00000
您可以将string.join与过滤器一起使用,以在一个或多个值为null或为空时删除重复的逗号。
Console.WriteLine(string.Join(",", new string[] { address1 , address2 , city , country , postalCode }.Where(c => !string.IsNullOrEmpty(c))));
Run Code Online (Sandbox Code Playgroud)