# Wednesday, January 31, 2007

This is free .NET code that converts the contents of an ArrayList to a comma delimited string, or any other character delimited string

The code calls the ToString() method on each item in the ArrayList, therefore if objects exist in the ArrayList, their ToString() method will be called and output to the delimited string.

  Public Shared Function ArrayListToDelimString(ByVal arrayList As ArrayList, ByVal separator As String) As String

    Dim stringArrayList As New ArrayList

    For Each o As Object In arrayList

      stringArrayList.Add(o.ToString())

    Next

    Return String.Join(separator, stringArrayList.ToArray(GetType(String)))

  End Function

 To illustrate its intended behavior, here is an example NUnit test (assumes function is placed in a "Utility" class):

Imports NUnit.Framework
Imports System.Text

<TestFixture()> Public Class TestUtility

  <Test()> Public Sub ArrayListToDelimString()

    Dim sb As New StringBuilder("3")

    Dim arrayList As New ArrayList
    arrayList.Add(1)
    arrayList.Add("2")
    arrayList.Add(sb)

    Assert.AreEqual("1,2,3", Utility.ArrayListToDelimString(arrayList, ",")) 'comma (CSV)
    Assert.AreEqual("1" & vbTab & "2" & vbTab & "3", Utility.ArrayListToDelimString(arrayList, vbTab)) 'tab
    Assert.AreEqual("1" & vbCrLf & "2" & vbCrLf & "3", Utility.ArrayListToDelimString(arrayList, vbCrLf))  '1 per line

    Console.Out.WriteLine(Utility.ArrayListToDelimString(arrayList, ","))
    Console.Out.WriteLine(Utility.ArrayListToDelimString(arrayList, vbTab))
    Console.Out.WriteLine(Utility.ArrayListToDelimString(arrayList, vbCrLf))

  End Sub

End Class

If you found this post helpful, please "Kick" it so others can find it too:

kick it on DotNetKicks.com
.NET | ASP.NET | NUnit | VB.NET