3

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

1
  • 2
    Any reason why you're using ArrayList instead of a generic collection? Commented Jan 14, 2011 at 17:21

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

String.Join(String, Object[]) was introduced in .NET Framework 4.
3

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

Comments

2

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();

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.