Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string array to int array

Tags:

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.

like image 242
Primetime Avatar asked Mar 08 '12 20:03

Primetime


2 Answers

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 
like image 139
Tim Schmelter Avatar answered Sep 19 '22 16:09

Tim Schmelter


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 
like image 23
Brad Falk Avatar answered Sep 20 '22 16:09

Brad Falk