问题
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.
回答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
回答2:
You can use the List(Of T).ConvertAll
Dim stringList = {'2','5','6'}.ToList
Dim intList = stringList.ConvertAll(Function(str) Int32.Parse(str))
回答3:
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
回答4:
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:
回答5:
My VB is rusty but I would do something like this:
intList = (From s in stringList Select CInt(s)).ToArray()
回答6:
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)
来源:https://stackoverflow.com/questions/24856591/how-to-convert-an-array-from-string-to-integer