tags:

views:

200

answers:

6

Quick question here. I'm converting an array into a string using String.Join. A small issue I have is that, in the array some index positions will be blank. An example is below:

array[1] = "Firstcolumn"
array[3] = "Thirdcolumn"

By using String.Join(",", array);, I'll get the following:

Firstcolumn,,Thirdcolumn

Note the extra ,. How can I remove the extra commas from the string, or ideally not include blank indices when using String.Join?

+1  A: 

You could use linq to remove the empty fields.

var joinedString = String.Join(",", array.Where(c => !string.IsNullOrEmpty(c));
Andy Rose
He asked specifically how, not just in theory, try supply code?
Richard J. Ross III
+21  A: 

Try this :):

var res = String.Join(",", array.Where(s => !string.IsNullOrEmpty(s)));

This will join only the strings which is not null or "".

lasseespeholt
I like the fact you are tackling the cause of the problem and not just bandaging the problem with a hack!
TK
Thanks buddy, thanks to everyone else too
Chris
+18  A: 

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)));
Bernhof
+1 for at the time of writing being the only answer to mention ToArray (which by the way is unnecessary in .NET 4).
Mark Byers
+1 For a .Net <= 4 solution :)
lasseespeholt
A: 

Extension method:

public static string ToStringWithoutExtraCommas(this object[] array)
{
    StringBuilder sb = new StringBuilder();
    foreach (object o in array)
    {

        if ((o is string && !string.IsNullOrEmpty((string)o)) || o != null)
            sb.Append(o.ToString()).Append(",");
    }

    sb.Remove(sb.Length - 1, 1);

    return sb.ToString();
}
Richard J. Ross III
This will not insert any commas at all. But he *wants* commas, just not after empty entries.
gehho
Oops, editing that, thanks
Richard J. Ross III
-1 a string can be empty without being null in which case the additional commas are included anyway.
Bernhof
Bernhof
Right I realized that And fixed it before you posted the comment, it works like a charm now!
Richard J. Ross III
I cancelled the downvote :)
Bernhof
Thank you very much
Richard J. Ross III
+1  A: 

Regular expression solution:

yourString = new Regex(@"[,]{2,}").Replace(yourString, @",");
Even Mien
+1  A: 
String.Join(",", array.Where(w => !string.IsNullOrEmpty(w));
madgnome