Louis Tran
Louis Tran

Reputation: 1156

How to convert an array from string to integer

I have an array "string()" with 3 element (2,5,6) How do I convert all of element from string to int? I tried CInt and Array.ConvertAll but they didn't work. Please show me the way to do that. Thank you.

Upvotes: 1

Views: 1995

Answers (6)

Jodrell
Jodrell

Reputation: 35696

Just use a lambda,

Dim intList As IList(Of Integer)
Dim list1 = "1,2,3".Split(",")
intList = list1.ConvertAll(Function(s) Integer.Parse(s))

or

Dim intList As IList(Of Integer)
Dim list1 = "1,2,3".Split(",")
intList = list1.ConvertAll(AddressOf Integer.Parse)

Upvotes: 0

Jonathan Allen
Jonathan Allen

Reputation: 70287

My VB is rusty but I would do something like this:

intList = (From s in stringList Select CInt(s)).ToArray()

Upvotes: 0

NeverHopeless
NeverHopeless

Reputation: 11233

This works like a charm:

    Dim strArr As New List(Of String)(New String() {"2", "5", "6"})
    Dim intList As List(Of Integer) = strArr.ConvertAll(New Converter(Of String, Integer)(AddressOf Integer.Parse))

No need to define a custom parser. Have look at its documentation as well:

Upvotes: 0

Suji
Suji

Reputation: 1326

Dim stringList() As String = {"2", "5", "6"}' string array 
Dim intList() As Integer = {0, 0, 0, 0, 0}'integer array initialized with 0
For i As Integer = 0 To stringList.Length - 1
    intList(i) = CInt(stringList(i))
Next
'Display the list
For i = 0 To intList.Length - 1
    MsgBox(intList(i))
Next

Upvotes: 0

Mark Hall
Mark Hall

Reputation: 54532

You have not said what type of problem you are having using Array.ConvertAll or shown your implementation of it, but this works for me.

Module Module1

    Sub Main()
        Dim mystringArray As String() = New String() {"2", "5", "6"}
        Dim myintArray As Integer()

        myintArray = Array.ConvertAll(mystringArray, New Converter(Of String, Integer)(AddressOf StringToInteger))
    End Sub

    Function StringToInteger(st As String) As Integer
        Return CInt(st)
    End Function

End Module

Upvotes: 1

NTK88
NTK88

Reputation: 593

You can use the List(Of T).ConvertAll

Dim stringList = {'2','5','6'}.ToList
Dim intList = stringList.ConvertAll(Function(str) Int32.Parse(str))

Upvotes: 0

Related Questions