Redim Preserve数组

时间:2016-05-19 14:55:22

标签: arrays vb.net jagged-arrays

我将元素添加到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

1 个答案:

答案 0 :(得分:1)

我认为您所看到的是redim语句,您正在设置数组中的项目总数,因此您需要做的就是将数组重新调整为您想要的大小,无需进行数学运算,记住array是基于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

或者您可以使用Array.Resize作为VisualVincent建议

Array.Resize(accelrates, 51)

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

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