Using the Cast Extension Method To Convert To String

N

Nathan Sokalski

I have a variable declared as followed:

Dim mylist As New Collections.Generic.List(Of Integer)

I want to use the String.Join() method to get a String like the following:

"1 3 5 7 9 2 4 6 8 0"

My first attempt to do this was the following:

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

However, this gives me the following error:

Unable to cast object of type 'System.Int32' to type 'System.String'.

I don't know what the Cast method tries to do to convert types (I'm going to
guess it uses CType, since that can supposedly be used for most types in
most cases), but I know that there are ways to convert an Integer to a
String. I tried all of the following, and they converted successfully:

CStr(myint)
myint.ToString()
CType(myint, String)

Is there a way to do what I want without writing my own function (with
methods like Cast and String.Join, there must be some way, right?)? I'm sure
I'm not the first person that wanted to make a List of Integers into a
String. Thanks.
 
A

Armin Zingler

Nathan said:
I have a variable declared as followed:

Dim mylist As New Collections.Generic.List(Of Integer)

I want to use the String.Join() method to get a String like the
following:

"1 3 5 7 9 2 4 6 8 0"

My first attempt to do this was the following:

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

However, this gives me the following error:

Unable to cast object of type 'System.Int32' to type 'System.String'.

I don't know what the Cast method tries to do to convert types (I'm
going to guess it uses CType, since that can supposedly be used for
most types in most cases), but I know that there are ways to convert
an Integer to a String. I tried all of the following, and they
converted successfully:

CStr(myint)
myint.ToString()
CType(myint, String)

Is there a way to do what I want without writing my own function (with
methods like Cast and String.Join, there must be some way, right?)?
I'm sure I'm not the first person that wanted to make a List of
Integers into a String. Thanks.

Cast casts only. Use Select instead:

Dim x = String.Join( _
" ", _
mylist.Select(Of String)(Function(value) value.ToString).ToArray)



Or the LINQ way:

Dim x = String.Join( _
" ", (From item In mylist Select s = item.ToString).ToArray)


Armin
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top