Home All Groups Group Topic Archive Search About

Using the Cast Extension Method To Convert To String

Author
28 May 2009 7:51 AM
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.
--
Nathan Sokalski
njsokal***@hotmail.com
http://www.nathansokalski.com/

Author
28 May 2009 8:15 AM
Armin Zingler
Nathan Sokalski wrote:
Show quoteHide quote
> 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