Add new value to integer array (Visual Basic 2010)

I have a dynamic integer array to which I want to add new values. How can i do this?

Dim TeamIndex(), i As Integer

For i = 0 to 100
    'TeamIndex(i).Add = <some value>
Next
+5
source share
2 answers

Use ReDim with Preserve to increase the size of the array while maintaining the old values.

ReDim in a loop is recommended if you do not know the size and find out that the size of the array is one by one.

Dim TeamIndex(), i As Integer

For i = 0 to 100
     ReDim Preserve TeamIndex(i)
    TeamIndex(i) = <some value>
Next

If you declare the size of the array later in the code in the frame, use

 ReDim TeamIndex(100)

Thus, the code will look like this:

Dim TeamIndex(), i As Integer
ReDim TeamIndex(100)
For i = 0 to 100
    TeamIndex(i) = <some value>
Next

You can use ArrayList / List (Of T) to add / remove values ​​more dynamically.

 Sub Main()
    ' Create an ArrayList and add three strings to it.
    Dim list As New ArrayList
    list.Add("Dot")
    list.Add("Net")
    list.Add("Perls")
    ' Remove a string.
    list.RemoveAt(1)
    ' Insert a string.
    list.Insert(0, "Carrot")
    ' Remove a range.
    list.RemoveRange(0, 2)
    ' Display.
    Dim str As String
    For Each str In list
        Console.WriteLine(str)
    Next
    End Sub

List (from T) MSDN

List (Of T) DotNetperls

+8
source

, , . ReDim Preserve - , , .

:

Dim TeamIndex(), i As Integer
For i = 0 to 100
  ReDim Preserve TeamIndex(i)
  TeamIndex(i) = <some value>
Next

, = 0, Common Language Runtime (CLR) :

  • , , ,
  • .

ArrayList , , , . , , , , , ArrayList , .

ReDim :

Dim MyArray() As XXX
Dim InxMACrntMax As Integer

ReDim MyArray(1000)
InxMACrntMax=-1

Do While more data to add to MyArray

  InxMACrntMax = InxMACrntMax + 1
  If InxMACrntMax > UBound(MyArray) Then
    ReDim Preserve MyArray(UBound(MyArray)+100)
  End If
  MyArray(InxMACrntMax) = NewValue

Loop                

ReDim MyArray(InxMACrntMax)    ' Discard excess elements

100 1000. , , .

+2

All Articles