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