1

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.

6 Answers 6

1

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
Sign up to request clarification or add additional context in comments.

Comments

0

You can use the List(Of T).ConvertAll

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

2 Comments

@user2584427, make sure to add System.Collections.Generic.
It still doesn't work after importing System.Collections.Generic
0
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

Comments

0

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:

Comments

0

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

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

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.