Convert string array to int array

后端 未结 6 1470
名媛妹妹
名媛妹妹 2021-02-04 03:42

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

6条回答
  •  一生所求
    2021-02-04 03:58

    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
    

提交回复
热议问题