97

How can I remove blank values from an array?

For example:

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

in this case, is there any method available to remove blank values from the array using C#?

At the end, I want to get an array in this format:

test={"1","2","3"}; 

which means 2 values removed from the array and eventually I get 3.

1
  • 1
    How do you get the array content, maybe something could be done their Commented Jan 11, 2012 at 6:00

5 Answers 5

243

If you are using .NET 3.5+ you could use LINQ (Language INtegrated Query).

test = test.Where(x => !string.IsNullOrEmpty(x)).ToArray(); 
Sign up to request clarification or add additional context in comments.

4 Comments

Should probably use String.IsNullOrEmpty to be safe, otherwise null values will make it into the new array.
I had to add x.Trim() to also get rid of values that contained only spaces : test = test.Where(x => !string.IsNullOrEmpty(x.Trim())).ToArray();
String.IsNullOrWhiteSpace would also work, then you wouldn't have to trim every value
Maybe I'm missing something but should there not be an extra "x" in there? test.Where(x => !string.IsNullOrEmpty()) not be test.Where(x => !string.IsNullOrEmpty(x)).
38

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

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

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

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

Comments

6

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

Comments

5

This might have been old, but you could try

string[] test = new[] { "1", "", "2", "", "3" }; test = string.Join(",", test).Split(new string[] { "," }, Stringsplitoptions.Removeemptyentries); 

Join the array and split again with the empty items removed.

1 Comment

This worked perfectly for me since I'm in an environment that doesn't support Linq. Thanks!
3

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

3 Comments

Good answer this is relevant if for example you're parsing a CSV file (or string) and you end up with fields that are filled with white spaces.
The IsNullOrWhiteSpace() method actually considers an empty string (with no whitespace) as having whitespace, so using both IsNullOrEmpty() and IsNullOrWhiteSpace() is redundant.
test = test.Where(x => !string.IsNullOrEmpty(x.Trim())).ToArray(); do the same trick and doesn't need to call it twice

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.