|
web
newsgroups
|
|||||||||||||||||||||||
|
|||||||||||||||||||||||
Using the Cast Extension Method To Convert To StringDim 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 wrote:
Show quoteHide quote > I have a variable declared as followed: Cast casts only. Use Select instead:> > 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. 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
Visual Studio 2008 hogging memory
ListView - Caching Thumbnails? partition numbers in four terms System.IO.File.Copy + NTFS Streams + special ACLs VS2010 for database developers How to catch page redirect exporting dataset to Excel is slow Converting from Access 32bit 64bit windows mobile pocketoutlook |
|||||||||||||||||||||||