How to create comma delimited string from ArrayList?

I save the ArrayList of identifiers in a processing script that I want to spit out as a comma-separated list for output to the debug log. Is there a way I can easily do this without getting hung up on things?

EDIT: Thanks to Joel for listing the (Of T) list available in .net 2.0 and higher. This makes TONS things easier if you have it.

+71
c # parsing
Oct 17 '08 at 18:28
source share
6 answers

Yes, I answer my question, but I have not found it here yet and thought it was a pretty smooth 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 β€œgain" for them is that an ArrayList should have items stored as strings if you use Option Strict to make sure the conversion is working properly.

EDIT: if you use .net 2.0 or higher, just create an object of type List (Of String) and you can get what you need. Thanks so much to Joel for this!

 String.Join(",", TargetList.ToArray()) 
+131
Oct 17 '08 at 18:30
source share

The solutions are still quite complicated. The idiomatic solution must be certain:

 String.Join(",", x.Cast(Of String)().ToArray()) 

There is no need for fantastic acrobatics in new versions of frames. Suppose this is not a very modern version, it would be simpler:

 Console.WriteLine(String.Join(",", CType(x.ToArray(GetType(String)), String()))) 

mspmsp the second solution is a good approach, but it does not work because it skips the AddressOf keyword. In addition, Convert.ToString quite inefficient (many unnecessary internal evaluations), and the Convert class is usually not very simple. I try to avoid this, especially since it is completely redundant.

+17
Oct 17 '08 at 19:03
source share

Something like:

 String.Join(",", myArrayList.toArray(string.GetType()) ); 

Which basically makes me know ...

EDIT

What about:

 string.Join(",", Array.ConvertAll<object, string>(a.ToArray(), Convert.ToString)); 
+16
Oct 17 '08 at 18:33
source share

string.Join(" ,", myArrayList.ToArray()); This will work with .net framework 4.5

+7
Feb 04 '16 at 10:19
source share
 foo.ToArray().Aggregate((a, b) => (a + "," + b)).ToString() 

or

 string.Concat(foo.ToArray().Select(a => a += ",").ToArray()) 

Update since it is very old. You should, of course, use string.Join now. This did not exist as an option at the time of writing.

+1
Oct 17 '08 at 18:47
source share

Here is a simple example demonstrating how to create a comma-delimited string using String.Join () from a list of strings:

 List<string> histList = new List<string>(); histList.Add(dt.ToString("MM/dd/yyyy::HH:mm:ss.ffff")); histList.Add(Index.ToString()); /*arValue is array of Singles */ foreach (Single s in arValue) { histList.Add(s.ToString()); } String HistLine = String.Join(",", histList.ToArray()); 
+1
Apr 17 2018-12-12T00:
source share



All Articles