简体   繁体   English

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

[英]Remove all empty elements from string array

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 foreach statement because that makes the code look ugly. 我想快速(可能通过LINQ)从中删除所有空元素("") )而不使用foreach语句,因为这会使代码看起来很难看。

You can use List.RemoveAll : 您可以使用List.RemoveAll

C# C#

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

VB.NET VB.NET

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

Check out with List.RemoveAll with String.IsNullOrEmpty() method; 使用String.IsNullOrEmpty()方法查看List.RemoveAll ;

Indicates whether the specified string is null or an Empty string. 指示指定的字符串是null还是空字符串。

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

Here is a DEMO . 这是一个DEMO

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM