How to join elements of an ArrayList converting it to a string representation?

15,336

Solution 1

In Framework 4 it is really simple:

var s = string.Join(",", myArrayList);

In 3.5 with LINQ's extension methods:

var s = string.Join(",", myArrayList.Cast<string>().ToArray());

These are shorter but not smarter.

I have no idea how they should be written with VB.NET.

Solution 2

I know this is an old question, but since I've had to work this out for myself today, I thought I'd post the VB.Net solution I came up with:

Private Function MakeCsvList() As String
  Dim list As New List(Of String)
  list.Add("101")
  list.Add("102")

  Return Strings.Join(list.ToArray, ",")
End Function

Solution 3

I would make it an extension method of ArrayList e.g.

public static string ToCsv(this ArrayList array)
{
    return String.Join(",", TryCast(array.ToArray(GetType(String)), String()))
}

Usage

string csv = myArrayList.ToCsv();
Share:
15,336
Max
Author by

Max

Updated on June 27, 2022

Comments

  • Max
    Max almost 2 years

    I 've an ArrayList and to join all its elements with a separator in one string I m using...

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

    however, I would know if there is a smarter/shorter method to get the same result, or same code that looks better...

    Thank You in advance,

    Max