C#: string[] to delimited string. Is there a one-liner?

XstreamINsanity picture XstreamINsanity · Aug 24, 2010 · Viewed 19.3k times · Source

What I'd prefer is something like:

string[] strArray = {"Hi", "how", "are", "you"};
string strNew = strArray.Delimit(chDelimiter);

However, there is no such function. I've looked over MSDN and nothing looked to me as a function that would perform the same action. I looked at StringBuilder, and again, nothing stood out to me. Does anyone know of a not to extremely complicated one liner to make an array a delimited string. Thanks for your guys' help.

UPDATE: Wow, lol, my bad. I kept looking at the .Join on the array itself and it was bugging the hell out of me. I didn't even look at String.Join. Thanks guys. Once it allows me to accept I shall. Preciate the help.

Answer

kbrimington picture kbrimington · Aug 24, 2010

For arrays, you can use:

string.Join(", ", strArray);

Personally, I use an extension method that I can apply to enumerable collections of all types:

public static string Flatten(this IEnumerable elems, string separator)
{
    if (elems == null)
    {
        return null;
    }

    StringBuilder sb = new StringBuilder();
    foreach (object elem in elems)
    {
        if (sb.Length > 0)
        {
            sb.Append(separator);
        }

        sb.Append(elem);
    }

    return sb.ToString();
}

...Which I use like so:

strArray.Flatten(", ");