4

How do I convert an arraylist into a string of comma delimated values in vb.net

I have an arraylist with ID values

arr(0)=1
arr(1)=2
arr(2)=3

I want to convert it into a string

Dim str as string=""
str="1,2,3"

4 Answers 4

10
str = string.Join(",", arr.ToArray());

If you need to convert the List to string[] before the string.Join you can do

Array.ConvertAll<int, string>(str.ToArray(), new Converter<int, string>(Convert.ToString));

So...

str = string.Join(",", Array.ConvertAll<int, string>(str.ToArray(), new Converter<int, string>(Convert.ToString)));
Sign up to request clarification or add additional context in comments.

Comments

4

You can simply achieve it from GetType and Join Functions.

Dim S = YourArrayList.ToArray(Type.GetType("System.String"))
MessageBox.Show(String.Join(",", S))

Another way is to use FOR EACH Statement to read and store each item of array one by one in a delimited string. (But not recommended)

Dim S as string = ""
For Each item As String In YourArrayList
    S &= item & ", "
Next
MessageBox.Show(S)

3 Comments

How is this different from the accepted answer two years ago or the one by @Redips77? Passing the type name as a string isn't an improvement
My answer is showing two ways this is the difference and no matter two and four years has passed, Many people are still searching for it and will be forever. This is not about an individual.
Didn't say it is - said it's not an improvement. Actually the second should be avoided at all costs as it creates temporary strings needlessly, resulting in memory waste and garbage collections. This will really hurt performance in server applications or when processing large arrays. As for the first way, it's worse than the second answer because you pass the type as a string when you could simply use typeof(String).
1

As the answer here you can try:

Dim s As String = String.Join(",", TryCast(arr.ToArray(GetType(String)), String()))

Comments

0

Use String.Join with a comma delimeter (http://msdn.microsoft.com/en-us/library/57a79xd0.aspx)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.