views:

689

answers:

3

What I'm looking for is a basic equivalent of JavaScript's Array::join() whereby you pass in a separator character and uses that in its return string of all the subscripts. I could certainly write my own function using a StringBuilder or whatnot, but there must be something built into the .NET BCL.

EDIT: Array of anything, not necessarily string or char. I'd prefer the method to simply call ToString() on each subscript object. String.Join() is great except that you pass it an array of strings.

+3  A: 

If the array contains strings, you can just use String.Join(). If the array does not contain strings, you'll need something a little more complicated so you can handle the cast or conversion process for each item it contains.

Update: Using @JaredPar's code as the basis for a more generic example:

char sep = GetSeparatorChar();
object[] toJoin = GetToJoin();
string joined = toJoin.Aggregate((x,y) => x.ToString()+sep.ToString()+y.ToString());

Obviously you could do anything you wanted to x and y in that example to get the string to look how you wanted.

Joel Coehoorn
Or use a StringBuilder :)
Jon Skeet
A: 

I'm unclear as to whether or not you are joining an array of characters or strings.

For Strings


char sep = GetSeparatorChar();
string[] toJoin = GetToJoin();
string joined = toJoin.Aggregate((x,y) => x+sep.ToString()+y);
JaredPar
+1  A: 

If String.Join doesn't do it for you - e.g. you have an IEnumerable<string> instead of a string[] or you have a collection of some other type, see this earlier question.

Jon Skeet