字符串数组中的空字段转换为'0'

时间:2014-10-31 11:09:30

标签: c# arrays string null

您好我有一堆字符串数组,字段中可能有空或无空格(见下文),如何使用最简单的代码将它们转换为字符串&#39; 0&#39;?< / p>

目标是转换以下数组

string[] NullFields = {"101.002","A","12","","3","","B"};

就像

string[] NullFields = {"101.002","A","12","0","3","0","B"};

非常感谢。

4 个答案:

答案 0 :(得分:1)

一个简单的循环怎么样?

for (int i = 0; i < NullFields.Length; i++) {
    if (string.IsNullOrEmpty(NullFields[i])
         NullFields[i] = "0";
}

答案 1 :(得分:0)

使用LINQ很容易:

string[] NullFields = {"101.002","A","12","","3","","B"}
                      .Select(x => string.IsNullOrEmpty(x) ? "0" : x)
                      .ToArray();

答案 2 :(得分:0)

首先是C#中的"" != null,两者之间存在巨大差异 - bedtime reading

其次,你走了:

var myArray = NullFields.Select(s => String.IsNullOrEmpty(s) ? "0" : s)
                        .ToArray();

答案 3 :(得分:0)



这将解决您的问题。

string[] NullFields = { "101.002", "A", "12", "", "3", "", "B" };
for (int i = 0; i < NullFields.Length; i++)
{
    if (NullFields[i] == null || NullFields[i] == "")
        NullFields[i] = "0";
}


希望它会对你有所帮助!