Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 533
Elmo Avatar asked Jan 13 '13 22:01

Elmo


People also ask

How do you remove empty elements from an array in Python?

The easiest way is list comprehension to remove empty elements from a list in Python. And another way is to use the filter() method. The empty string "" contains no characters and empty elements could be None or [ ], etc.


2 Answers

You can use List.RemoveAll:

C#

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

VB.NET

s.RemoveAll(Function(str) String.IsNullOrEmpty(str)) 
like image 178
Tim Schmelter Avatar answered Sep 22 '22 17:09

Tim Schmelter


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

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

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

Here is a DEMO.

like image 41
Soner Gönül Avatar answered Sep 20 '22 17:09

Soner Gönül