I have tried a couple different ways and cannot seem to get the result I want using vb.net.
I have an array of strings. {"55555 ","44444", " "}
I need an array of integers {55555,44444}
This is a wpf page that is sending the array as a parameter to a crystal report.
Any help is appreciated.
You can use the List(Of T).ConvertAll
method:
Dim stringList = {"123", "456", "789"}.ToList Dim intList = stringList.ConvertAll(Function(str) Int32.Parse(str))
or with the delegate
Dim intList = stringList.ConvertAll(AddressOf Int32.Parse)
If you only want to use Arrays, you can use the Array.ConvertAll method
:
Dim stringArray = {"123", "456", "789"} Dim intArray = Array.ConvertAll(stringArray, Function(str) Int32.Parse(str))
Oh, i've missed the empty string in your sample data. Then you need to check this:
Dim value As Int32 Dim intArray = (From str In stringArray Let isInt = Int32.TryParse(str, value) Where isInt Select Int32.Parse(str)).ToArray
By the way, here's the same in method syntax, ugly as always in VB.NET:
Dim intArray = Array.ConvertAll(stringArray, Function(str) New With { .IsInt = Int32.TryParse(str, value), .Value = value }).Where(Function(result) result.IsInt). Select(Function(result) result.Value).ToArray
You can use the Array.ConvertAll method:
Dim arrStrings() As String = {"55555", "44444"} Dim arrIntegers() As Integer = Array.ConvertAll(arrStrings, New Converter(Of String, Integer)(AddressOf ConvertToInteger)) Public Function ConvertToInteger(ByVal input As String) As Integer Dim output As Integer = 0 Integer.TryParse(input, output) Return output End Function
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With