【问题标题】:Redim Preserve arrayRedim Preserve 数组
【发布时间】:2016-09-16 13:19:10
【问题描述】:

我正在向 listOF 添加元素,然后将该列表转换为数组。然后,我需要向每个数组添加特定数量的元素,同时还要保留每个元素中的数据。我很近,但还没有。

这不起作用。该数据保留在元素中,但代码并未将指定数量的元素添加到每个数组(每个数组需要 = 51)。

一如既往地感谢任何帮助。谢谢。

 'Add an element to each ListOf(Integer) based on how many rows are in the DataGridView
        For Each r As DataGridViewRow In dgvStepTest.Rows
            accels.Add(r.Cells(0).Value) : decels.Add(r.Cells(1).Value) : Speeds.Add(r.Cells(2).Value)
            holds.Add(r.Cells(3).Value) : flows.Add(r.Cells(4).Value) : Temps.Add(r.Cells(5).Value)
        Next

        'Convert each ListOf(Integer) to an Array
        accels.TrimExcess() : accelRates = accels.ToArray
        decels.TrimExcess() : decelRates = decels.ToArray
        Speeds.TrimExcess() : spindleSpeeds = Speeds.ToArray
        holds.TrimExcess() : holdTimes = holds.ToArray
        flows.TrimExcess() : flowRates = flows.ToArray
        Temps.TrimExcess() : oilTemps = Temps.ToArray

        'Now determine the number of elements to add to each of the arrays so that the length of each array = 51
        num = (51 - accelRates.Length)

        'Now add the number of elements to each array based on the number calculated above, while also preserving the data
        'already in each element in each of the arrays.  New elements added should have values = 0.
        Dim jaggedArray()() = New Integer(5)() {accelRates, decelRates, spindleSpeeds, holdTimes, flowRates, oilTemps}
        For Each [Array] In jaggedArray
            ReDim Preserve Array(Array.Length + num)
        Next

【问题讨论】:

  • 改用Array.Resize()。还可以使用调试器单步执行您的代码以验证所有变量。
  • 您是否有理由想要增加数组的大小(这很昂贵),而不是在将其转换为数组之前将额外的项目添加到您的列表中?
  • 马克,感谢您的反馈。不,没有理由,因此我已经返回并更改了它,以便将额外的元素添加到列表中,然后转换为数组。所以,我正在完成我需要做的事情,即使它不符合最初的计划。不过,谢谢你的收获。话虽如此,我仍然想根据自己的知识制作原始作品,并且可能需要在某些时候使用它。

标签: arrays vb.net jagged-arrays


【解决方案1】:

我认为您看到的是 redim 语句,您正在设置数组中的项目总数,因此您需要做的就是将数组重新调整为您想要的大小,无需进行数学运算,记住数组是基于 0 的,这意味着使用 redim 语句设置数组大小为 51 实际上将有 52 条记录。这是一个快速的小测试来说明我的意思。

Module Module1
    Sub Main()
        Dim accels As List(Of Integer) = New List(Of Integer)()
        accels.AddRange({0, 1, 2, 3, 4, 5, 6, 7, 8, 9})
        Dim accelrates = accels.ToArray()
        Dim num As Integer = (50) ' Index is zero based there for use 50
        ReDim Preserve accelrates(num)
    End Sub
End Module

或者您可以按照 VisualVincent 的建议使用 Array.Resize

Array.Resize(accelrates, 51)

再进一步看,您的For Each 语句似乎没有按预期工作。我会把它改成 For 这样的声明。

For x = 0 To jaggedArray.Count - 1
    ReDim Preserve jaggedArray(x)(50)
Next

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-07
    • 1970-01-01
    • 2010-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多