Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a comma delimited string from an ArrayList?

Tags:

c#

parsing

vb.net

I'm storing an ArrayList of Ids in a processing script that I want to spit out as a comma delimited list for output to the debug log. Is there a way I can get this easily without looping through things?

EDIT: Thanks to Joel for pointing out the List(Of T) that is available in .net 2.0 and above. That makes things TONS easier if you have it available.

like image 811
Dillie-O Avatar asked Oct 17 '08 18:10

Dillie-O


People also ask

How do you convert an ArrayList to a comma-separated string in Java?

We can convert ArrayList to a comma-separated String using StringJoiner which is a class in java. util package which is used to construct a sequence of characters(strings) separated by a delimiter and optionally starting with a supplied prefix and ending with a supplied suffix.

How do you turn an ArrayList into a string?

To convert the contents of an ArrayList to a String, create a StringBuffer object append the contents of the ArrayList to it, finally convert the StringBuffer object to String using the toString() method.

How do you add comma-separated Values in an ArrayList?

All you need to do is first split the given String on delimiter e.g. comma using the split() method, this will give you an array of String. Now, you can pass that array to Arrays. asList() method to create a list, but remember this would be a fixed-length list and not truly an ArrayList.

How do you convert an array to a comma with strings?

To convert an array to a comma-separated string, call the join() method on the array, passing it a string containing a comma as a parameter. The join method returns a string containing all array elements joined by the provided separator.


1 Answers

Yes, I'm answering my own question, but I haven't found it here yet and thought this was a rather slick thing:

...in VB.NET:

String.Join(",", CType(TargetArrayList.ToArray(Type.GetType("System.String")), String())) 

...in C#

string.Join(",", (string[])TargetArrayList.ToArray(Type.GetType("System.String"))) 

The only "gotcha" to these is that the ArrayList must have the items stored as Strings if you're using Option Strict to make sure the conversion takes place properly.

EDIT: If you're using .net 2.0 or above, simply create a List(Of String) type object and you can get what you need with. Many thanks to Joel for bringing this up!

String.Join(",", TargetList.ToArray()) 
like image 196
Dillie-O Avatar answered Oct 06 '22 03:10

Dillie-O