c# - 具有空值 C# 的 String.Format

标签 c# .net c#-4.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);

不幸的是,当 Line2、Line3、Line4 为空时,这将生成 116 Knox St, , , , Watson, ACT, 2602。我如何处理空值以获得类似 116 Knox St, Watson, ACT, 2602 的结果?

最佳答案

看起来这样可以更简洁地实现您的目的。

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

关于c# - 具有空值 C# 的 String.Format,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20532700/

相关文章:

c# - 使用 JsonUtility 反序列化嵌套对象

c# - 查询 Active Directory 中 OU 中的所有用户并将用户名输出到列表框

c# - 内部列表上的 Entity Framework 过滤器

c# - 来自动态代码的异常堆栈跟踪中的文件路径和行号错误

.net - 远程点网应用

.net - EF 4.x 和交易

c# - 在c#中删除 ""之间的逗号

c# - 在 .NET 中有什么方法,除了 Oledb 是独立于数据库的

c# - 通过编码在 C# .Net 中自动生成索引

c# - 如何使用c#获取任务栏中应用程序的进程名称?