tags:

views:

507

answers:

3

Is there an easy way to convert a string array into a concantenated string?

For example, I have a string array:

new string[]{"Apples", "Bananas", "Cherries"};

And I want to get a single string:

"Apples,Bananas,Cherries"

Or "Apples&Bananas&Cherries" or "Apples\Bananas\Cherries"

+18  A: 

A simple one...

string[] theArray = new string[]{"Apples", "Bananas", "Cherries"};
string s = string.Join(",",theArray);
Marc Gravell
Hey, I knew that really. It's just very hot in the office today and I haven't had a coffee! Thanks.
Moose Factory
Although it feels a bit odd. It think it is more an action on an array than an action on a string so it would be more "natural" for me to look for such a function in the array class. But thanks, I did not know there was such a way to join a string[] (so no more for constructions)! +1
Gertjan
But it would only apply to `string[]`, not to any others - so it doesn't fit cleanly into the "regular" array implementation. But you could add it as a C# 3.0 *extension method* to `this string[]`.
Marc Gravell
Why should you only be able to use string[] and not any type of array. I think it would be possible to just use the ToString() method of the objects in the array (at least I would do it that way) so you can also Join arrays of integers, longs and even complex objects (even your own objects when implementing the ToString). I don't know how other languages solve this, but because it was not in the array class I never noticed it (and creating a for was quicker than doing research on the internet).
Gertjan
Then write a `Join<T>(this T[] array)` extension method ;-p
Marc Gravell
+7  A: 

String.Join Method (String, String[])

rahul
+4  A: 

The obvious choise is of course the String.Join method.

Here's a LINQy alternative:

string.Concat(fruit.Select((s, i) => (i == 0 ? "" : ",") + s).ToArray())

(Not really useful as it stands as it does the same as the Join method, but maybe for expanding where the method can't go, like alternating separators...)

Guffa