使用 c# 删除数组中的空白值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8814811/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 04:34:46  来源:igfitidea点击:

Remove blank values in the array using c#

c#

提问by Mulesoft Developer

Is there any method which remove blank indexs from the array e.g

是否有任何方法可以从数组中删除空白索引,例如

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

in this case is there any metod available to remove blank index from the array using c# at the end i want to get array in this format test={"1","2","3"};which mean two index remove from the array and finaly i got 3 index I'am not wriing exact code for array this is hint which i want to do

在这种情况下,是否有任何方法可用于在最后使用 c# 从数组中删除空白索引我想以这种格式获取数组,这 test={"1","2","3"};意味着从数组中删除两个索引,最后我得到了 3 个索引我没有为数组这是我想做的提示

采纳答案by xandercoded

If you are using .NET 3.5+ you could use linq.

如果您使用 .NET 3.5+,则可以使用 linq。

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

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

回答by ChrisWue

You can use Linq in case you are using .NET 3.5 or later:

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

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

If you can't use Linq then you can do it like this:

如果你不能使用 Linq,那么你可以这样做:

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

回答by Ateeq

I prefer to use two options, white spaces and empty:

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

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

回答by Sunil Dhappadhule

I write below code to remove the blank value in the array string.

我写下面的代码来删除数组字符串中的空白值。

string[] test={"1","","2","","3"};
test= test.Except(new List<string> { string.Empty }).ToArray();