Elmo
Elmo

Reputation: 6471

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.

Upvotes: 42

Views: 57023

Answers (4)

SUNIL DHAPPADHULE
SUNIL DHAPPADHULE

Reputation: 2863

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

Upvotes: 0

Muhammad Hani
Muhammad Hani

Reputation: 8664

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

Upvotes: 11

Soner G&#246;n&#252;l
Soner G&#246;n&#252;l

Reputation: 98750

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.

Upvotes: 14

Tim Schmelter
Tim Schmelter

Reputation: 460098

You can use List.RemoveAll:

C#

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

VB.NET

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

Upvotes: 67

Related Questions