C# 从字符串数组中删除所有空元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14309072/
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-10 11:23:46  来源:igfitidea点击:

Remove all empty elements from string array

c#.netvb.netlinqlist

提问by Elmo

I have this:

我有这个:

List<string> s = new List<string>{"", "a", "", "b", "", "c"};

I want to remove all the empty elements ("")from it quickly (probably through LINQ) without using a foreachstatement because that makes the code look ugly.

我想在("")不使用foreach语句的情况下快速(可能通过 LINQ)从中删除所有空元素,因为这会使代码看起来很丑陋。

采纳答案by Tim Schmelter

You can use List.RemoveAll:

您可以使用List.RemoveAll

C#

C#

s.RemoveAll(str => String.IsNullOrEmpty(str));

VB.NET

网络

s.RemoveAll(Function(str) String.IsNullOrEmpty(str))

回答by MuhammadHani

s = s.Where(val => !string.IsNullOrEmpty(val)).ToList();

回答by Soner G?nül

Check out with List.RemoveAllwith String.IsNullOrEmpty()method;

List.RemoveAll使用String.IsNullOrEmpty()方法结帐;

Indicates whether the specified string is null or an Empty string.

指示指定的字符串是空字符串还是空字符串。

s.RemoveAll(str => string.IsNullOrEmpty(str));

Here is a DEMO.

这是一个DEMO.

回答by Sunil Dhappadhule

I write below code to remove the blank value

我写下面的代码来删除空白值

List<string> s = new List<string>{"", "a", "", "b", "", "c"};
s = s.Where(t => !string.IsNullOrWhiteSpace(t)).Distinct().ToList();