tags:

views:

227

answers:

3

Hi,

is there any method in c# thats equivalent to the javascript join()..

   var keyStr = keyList.join("_");

My requirement is to concatenate the array of strings into an single string with the given separator.

And i wanted to convert my whole string array into an single string... in javascript we can do this by calling toString() of the jabvascript array

C# toString of an array just prints the type information. If we use toString on other types like int, it returns the string representation of an int. But why this is been not implemented in String array. wouldnt that strange??

And

Cheers

Ramesh Vel

+5  A: 

You can use string.Join():

string.Join("_", array);

or, for lists:

string.Join("_", list.ToArray());

Converting a string array into a single string is done exactly the same way: With string.Join():

string.Join(" ", stringarray);

Dan Elliott also has a nice extension method you can use to be a little closer to JavaScript, syntax-wise.

Joey
thanks johannes. Join works perfectly, but my second requirement is to convert string array into an single string value...
Ramesh Vel
@Ramesh you can either use String.Join("", stringArray) or String.Concat(stringArray)
Richard Szalay
Sorry, misread you ... twice by now ... need ... more ... coffee ...
Joey
:) thanks guys.... it works
Ramesh Vel
A: 

Try the code below.

 string[] arr=new string[]{"aa","bb","cc"};
 string.Join("-", arr);
Himadri
+2  A: 

if you wish to add the functionality to a string array you could do with an extension method

public static class ArrayExtension
{

  public static string AsString(this string[] array, string seperator)
  {
    return string.Join(seperator, array);
  }
}

Then you would write:

var keyStr = keyList.AsString("_");
Daniel Elliott
thanks Dan, looks closely javacript...
Ramesh Vel