Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 864
XstreamINsanity Avatar asked Sep 05 '25 03:09

XstreamINsanity


2 Answers

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(", ");
like image 154
kbrimington Avatar answered Sep 07 '25 20:09

kbrimington


You can use the static String.Join method:

String strNew = String.Join(chDelimiter, strArray);


EDIT: In response to comment: Based on your comment, you can take several arrays, concatenate them together, and then join the entire resulting array. You can do this by using the IEnumerable extension method Concat. Here's an example:

//define my two arrays...
string[] strArray = { "Hi", "how", "are", "you" };
string[] strArray2 = { "Hola", "como", "esta", "usted" };

//Concatenate the two arrays together (forming a third array) and then call join on it...
string strNew = String.Join(",", strArray.Concat(strArray2));

Hope this helps!

like image 22
David Hoerster Avatar answered Sep 07 '25 20:09

David Hoerster