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

9

90

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.

Pharyngeal answered 17/10, 2008 at 18:28 Comment(2)
I presume, because you're using an ArrayList, you're using .Net 1.0 or .Net 1.1?Slr
#799946Corpulent
P
171

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())
Pharyngeal answered 17/10, 2008 at 18:30 Comment(3)
There are other "gotchas". One being that this solution isn't as idiomatic as looping through the list yourself. Second, if ToArray traverses the collection, and Join does too, this takes twice as long as a simple foreach loop.Shouldst
Of course there's always the possibility of using System.Collections.Specialized.StringCollection.Sternpost
If you can consider using a List<string> instead, that has a built-in ToArray() method, and eliminiates type issues. BTW - typeof(string) is preferable to Type.GetType("System.String").Fireside
M
17

The solutions so far are all quite complicated. The idiomatic solution should doubtless be:

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

There's no need for fancy acrobatics in new framework versions. Supposing a not-so-modern version, the following would be easiest:

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

mspmsp's second solution is a nice approach as well but it's not working because it misses the AddressOf keyword. Also, Convert.ToString is rather inefficient (lots of unnecessary internal evaluations) and the Convert class is generally not very cleanly designed. I tend to avoid it, especially since it's completely redundant.

Mahone answered 17/10, 2008 at 18:28 Comment(2)
Aren't CType and CStr are essentially calls into the Convert class?Cilka
@Echostorm: where do I say that? @Joel: not at all. Most of the time, they call the MS.VB.CS.Conversions.ToString helper function which results in a simple ToString call. But even this method I wouldn't call directy (as opposed to through the VB cast operators).Mahone
A
16

Something like:

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

Which basically loops ya know...

EDIT

how about:

string.Join(",", Array.ConvertAll<object, string>(a.ToArray(), Convert.ToString));
Auriol answered 17/10, 2008 at 18:33 Comment(1)
oops.... that's not right... how about: string.Join(",", Array.ConvertAll<object, string>(a.ToArray(), Convert.ToString));Auriol
B
8

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

Barrios answered 4/2, 2016 at 10:19 Comment(0)
S
2
foo.ToArray().Aggregate((a, b) => (a + "," + b)).ToString()

or

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

Updating, as this is extremely old. You should, of course, use string.Join now. It didn't exist as an option at the time of writing.

Stealing answered 17/10, 2008 at 18:47 Comment(1)
Wow, I'm really sorry! I completely overlooked the “C#” tag on the question and surmised your answers were meant to be valid VB code. Shame on me. But while we're nitpicking: your second answer appends an extra “,” at the end.Mahone
S
2

Here's a simple example demonstrating the creation of 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());
Selfknowledge answered 17/4, 2012 at 13:4 Comment(0)
N
0

So far I found this is a good and quick solution

//CPID[] is the array
string cps = "";
if (CPID.Length > 0)
{   
    foreach (var item in CPID)
    {
        cps += item.Trim() + ",";
    }
}
//Use the string cps
Nyaya answered 9/1, 2021 at 6:33 Comment(0)
D
0

Try this, either one works!

string[] myArray = {"Start", "Stop", "Pause"};

// Option #1
var result = string.Join("|", myArray)

// Option #2
result = myArray.Aggregate(string.Empty, (x, y) => (string.IsNullOrEmpty(x) ? string.Empty : $"{x}|") + y)
Devan answered 28/6, 2024 at 18:1 Comment(0)
C
-1

Just because the answer I liked, had the comma the wrong way around making a CSV list of names look like this:

Rob ,Steve ,Ben

Instead this is what you should want:

Rob, Steve, Ben

So only a small change will be needed using the latest VS/C# 2022:

ArrayList names = new ArrayList();

names.Add("Rob");
names.Add("Steve");
names.Add("Ben");

string namelist = String.Join(", ", names.ToArray());

Console.WriteLine(namelist);
Ceramal answered 6/1, 2023 at 2:6 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.