使用C#从数组中删除空白值


76

如何从数组中删除空白值?

例如:

string[] test={"1","","2","","3"};

在这种情况下,是否有任何方法可以使用C#从数组中删除空白值?

最后,我要获取以下格式的数组:

test={"1","2","3"};

这意味着从数组中删除了2个值,最终得到3个值。


1
您如何获取阵列内容,也许可以做些什么
V4Vendetta 2012年

Answers:


192

如果使用的是.NET 3.5+,则可以使用LINQ(语言集成查询)。

test = test.Where(x => !string.IsNullOrEmpty()).ToArray();

2
为了安全起见,应该使用String.IsNullOrEmpty,否则null值会将其放入新数组。
apiguy 2012年

4
我必须添加x.Trim()来消除仅包含空格的值:test = test.Where(x =>!string.IsNullOrEmpty(x.Trim()))。ToArray();
GuidoG '16

7
String.IsNullOrWhiteSpace也可以使用,那么您不必
精简

34

如果您使用的是.NET 3.5或更高版本,则可以使用Linq:

 test = test.Where(x => !string.IsNullOrEmpty(x)).ToArray();

如果您不能使用Linq,则可以这样做:

var temp = new List<string>();
foreach (var s in test)
{
    if (!string.IsNullOrEmpty(s))
        temp.Add(s);
}
test = temp.ToArray();


2

我更喜欢使用两个选项,空白和空:

test = test.Where(x => !string.IsNullOrEmpty(x)).ToArray();
test = test.Where(x => !string.IsNullOrWhiteSpace(x)).ToArray();

好的答案很重要,例如,如果您正在解析CSV文件(或字符串),而最终得到的字段都是空白。
塔希尔·哈立德

2
IsNullOrWhiteSpace()方法实际上将空字符串(不带空格)视为具有空格,因此同时使用IsNullOrEmpty()和IsNullOrWhiteSpace()是多余的。
aardvark
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.