How to get sub-array from larger array in VB.NET?

后端 未结 3 1277
梦毁少年i
梦毁少年i 2021-01-13 23:06

I have:

Dim arr() As String = {\"one\",\"two\",\"three\"}

I want a new array, sub, containing {\"one\", \"three\"} only. What

3条回答
  •  情话喂你
    2021-01-13 23:39

    It's a little difficult to see what you want exactly, but something like this will work.

    Dim arr() As String = {"one","two","three"}
    
    Dim templist As New List(Of String)(arr)
    templist.RemoveAt(1)
    Dim sub() As String = templist.ToArray()
    

    Personally, I'd be using List rather than String() if you want to make frequent changes like this.


    EDIT: Considering RPK's comment below:

    Function RemoveElements(ByVal arr() As String, ByVal ParamArray skip() As Integer) As String()
        Dim templist As New List(Of String)(arr.Length - skip.Length)
        For i As Integer = 0 to templist.Length - 1
            if Array.IndexOf(skip, i) = -1 Then templist.Add(arr(i))
        Next i
        Return templist.ToArray()
    End Function
    

    You can call this for a single element:

    ' Skips the second element.
    Dim sub() As String = RemoveElements(arr, 1)
    

    or with as many elements as you like:

    ' Skips the second, fourth, seventh and eleventh elements.
    Dim sub() As String = RemoveElements(arr, 1, 3, 6, 10)
    

    or with an array:

    ' Skips the second, fourth, seventh and eleventh elements.
    Dim skip() As Integer = {1, 3, 6, 10}
    Dim sub() As String = RemoveElements(arr, skip)
    

    Note, this is slow code, but it can make your code easier to read and maintain.

提交回复
热议问题