【问题标题】:Add new value to integer array (Visual Basic 2010)向整数数组添加新值 (Visual Basic 2010)
【发布时间】:2012-05-21 16:21:12
【问题描述】:

我有一个动态整数数组,我希望向其中添加新值。我该怎么做?

Dim TeamIndex(), i As Integer

For i = 0 to 100
    'TeamIndex(i).Add = <some value>
Next

【问题讨论】:

    标签: vb.net arrays


    【解决方案1】:

    使用 ReDim 和 Preserve 来增加数组的大小并保留旧值。

    当您不知道大小并知道要逐个增加数组大小时,建议使用循环中的 ReDim。

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

    如果您稍后在镜头中的代码中声明数组的大小,请使用

     ReDim TeamIndex(100)
    

    所以代码将是:

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

    您可以使用 ArrayList/List(Of T) 更动态地使用添加/删除值。

     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(Of T) MSDN

    List(Of T) DotNetperls

    【讨论】:

    • 无需重新调整和保留。只需初始化大小为 100 的数组 [假设大小为 100]
    • For i=0 to SomeNo。因此,如果数组将被初始化As New Integer(SomeNo)ReDimPreserve 在这种情况下将不需要 [Example by asker] 因为SomeNo 是常量。因此,如果SomeNo 也是可变的并且不断变化,那么ReDimPreserve 将是必要的!
    • +1 但对于新代码,List(Of T) 应该优先于 ArrayList
    【解决方案2】:

    Romil 的回答中没有什么我认为是错误的,但我会更进一步。 ReDim Preserve 是一个非常有用的命令,但重要的是要意识到它是一个昂贵的命令并明智地使用它。

    考虑:

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

    对于每个循环,除了 i=0,公共语言运行时 (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。我选择的值取决于我对可能需求的评估。

    【讨论】:

      猜你喜欢
      • 2022-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多