Removing extra commas from string after using String.Join to convert array to string (C#)

Viewed 13582

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?

9 Answers
string.Join(",", string.Join(",", array).Split({","}, StringSplitOptions.RemoveEmptyEntries));

v('_')V

Simple extension method

namespace System
{
    public static class Extenders
    {
        public static string Join(this string separator, bool removeNullsAndWhiteSpaces, params string[] args)
        {
            return removeNullsAndWhiteSpaces ? string.Join(separator, args?.Where(s => !string.IsNullOrWhiteSpace(s))) : string.Join(separator, args);
        }
        public static string Join(this string separator, bool removeNullsAndWhiteSpaces, IEnumerable<string> args)
        {
            return removeNullsAndWhiteSpaces ? string.Join(separator, args?.Where(s => !string.IsNullOrWhiteSpace(s))) : string.Join(separator, args);
        }
    }
}

Usage:

var str = ".".Join(true, "a", "b", "", "c");
//or 
var arr = new[] { "a", "b", "", "c" };
str = ".".Join(true, arr);
Related