sproketboy
sproketboy

Reputation: 9452

VB How to Insert into an array at the specified index

Trying to figure this out. I don't any helper methods for this.

I want to insert an element into an array at a specified index and resize and preserve the other values - which should just be shifted down.

Here's an example:

        Dim a1(9)  As Integer
        For i As Integer = 0 To a1.Length - 1
            a1(i) = -1
        Next

        For i As Integer = 0 To a1.Length - 1
            Console.WriteLine(i & " " & a1(i))
        Next
        Console.WriteLine("--------------")

        ReDim Preserve a1(10)
        For i As Integer = 0 To a1.Length - 1
            Console.WriteLine(i & " " & a1(i))
        Next

        ' at this point I have size 10
        ' I want to insert say 99 at index 4
        Dim index As Integer
        index = 4

' before 
'        0 0
'        1 -1
'        2 -2
'        3 -3
'        4 -4
'        5 -5
'        6 -6
'        7 -7
'        8 -8
'        9 -9
'        10 0

' after
'        0 0
'        1 -1
'        2 -2
'        3 -3
'        4 99
'        5 -4
'        6 -5
'        7 -6
'        8 -7
'        9 -8
'        10 -9

Upvotes: 0

Views: 1385

Answers (1)

Alex B.
Alex B.

Reputation: 2167

Swap the other index values and then set the new value:

 For i as Integer = a1.Length -1 to index step -1 
    a1(i) = a1(i-1)
 Next
 a1(index) = 99

Fiddle

Upvotes: 1

Related Questions