开发者

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

开发者 https://www.devze.com 2023-02-04 22:55 出处:网络
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

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


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.


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


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

精彩评论

暂无评论...
验证码 换一张
取 消