Removing extra commas from string after using String.Join to convert array to string (C#)
Try this :):
var res = string.Join(",", array.Where(s => !string.IsNullOrEmpty(s)));
This will join only the strings which is not null
or ""
.
A simple solution would be to use linq, by filtering out the empty items before joining.
// .net 3.5
string.Join(",", array.Where(item => !string.IsNullOrEmpty(item)).ToArray());
In .NET 4.0 you could also make use of string.IsNullOrWhiteSpace
if you also want to filter out the items that are blank or consist of white space characters only (note that in .NET 4.0 you don't have to call ToArray
in this case):
// .net 4.0
string.Join(",", array.Where(item => !string.IsNullOrWhiteSpace(item)));
You could use linq to remove the empty fields.
var joinedString = String.Join(",", array.Where(c => !string.IsNullOrEmpty(c));