我想格式化一个地址。这是我的代码:
address = String.Format("{0}, {1}, {2}, {3}, {4}, {5}, {6}",
postalAddress.Line1,
postalAddress.Line2,
postalAddress.Line3,
postalAddress.Line4,
postalAddress.Suburb,
postalAddress.StateCode,
postalAddress.Pcode);
不幸的是,当Line2,Line3,Line4为空时,这会产生116 Knox St, , , , Watson, ACT, 2602
。如何处理空值以获得116 Knox St, Watson, ACT, 2602
的结果?
答案 0 :(得分: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 :(得分: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(',');
答案 2 :(得分: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
以格式化方式附加字符串,你可以试验并玩弄它,直到它按照你喜欢的方式运行,然后你可以将它重构为一堆更少的线条!
答案 3 :(得分: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");