views:

1747

answers:

6

Ok, this is a dumb thing that I'm sure I've done dozens of times but for some reason I can't find it.

I have an array... And want to get a string with the contents of that array separated by a delimited...

Where is the .Join() method that I can't find?

(This is .Net 2.0, I don't have any LINQ stuff)

Thank you!

+9  A: 

If you're working with strings, then String.Join is probably what you're looking for.

Craig
+6  A: 

It is on the string class

String.Join(",", new string[] {"a", "b", "c"});

Edit for ints to string

 int[] integers = new int[] { 1,2,3,4,5 };
 String.Join(",", Array.ConvertAll<int, String>(integers, Convert.ToString));
Bob
+2  A: 

If you have an array of strings you can call String.join(String, String[]). You can use it even if you don't have an array of strings, you just have to be able to convert your objects to strings

object[] objects = ...
string[] strings = new string[objects.Length];
for (int i = 0; i < objects.Length; i++)
  strings[i] = objects[i].ToString();
string value = String.Join(", ", strings);
Samuel
A: 

Thanks for your answers!! That's what I was looking for.

Now, the Array is full of integers... Any nice, expressive way to convert it to an array of strings? (something like a map(myArray, CInt), which I know isn't possible), or to call Join on it directly?

Daniel Magliola
A: 

You can find the method in the String class.

Example using Split and Join:

 public static void Main() { 

    string str = "on two three, four five six."; 
    char[] separators = {' ', '.', ',' }; 

    // Split the string:
    string[] parts = str.Split(separators); 

    string allTogether = String.Join(" | ", parts); 

    Console.WriteLine("Joined: "); 
    Console.WriteLine(allTogether); 


  }
splattne
+1  A: 

You could use LINQ to Objects and save yourself a few lines

int [] ints = { 0, 1, 2 };
string[] intStrings = (from i in ints select i.ToString()).ToArray<string>();
string joinedStrings = string.Join(",", intStrings);

Oops, Just saw that you don't have LINQ, sorry.

Nick