开发者

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 buggi开发者_StackOverflow社区ng 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.


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(", ");


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!


Have a look at String.Join().

Your sample must look like this :

        string delimiter = ","
        string[] strArray = { "Hi", "how", "are", "you" };
        string strNew = String.Join(delimiter, strArray);


Use String.Join

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


in this case, String.Join() is probably the easiest way to go, you can equally use LINQ though

var comSeparatedStrings = strings.Aggregate((acc, item) => acc + ", " + item);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜