Remove blank values from array using C#
C#C# Problem Overview
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.
C# Solutions
Solution 1 - C#
If you are using .NET 3.5+ you could use LINQ (Language INtegrated Query).
test = test.Where(x => !string.IsNullOrEmpty(x)).ToArray();
Solution 2 - C#
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();
Solution 3 - C#
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();
Solution 4 - C#
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();
Solution 5 - C#
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.