busarider29 busarider29 - 5 months ago 10x
Vb.net Question

Redim Preserve array

I am adding elements to a listOF and then converting that list to an array. I then need to add a specific number of elements to each of the arrays while also preserving the data in each element. I am close but not there yet.

This is not working. That data is preserved in the elements but the code is not adding the specified number of elements to each array (each array needs to = 51).

Any help is appreciated as always. Thank you.

'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)

'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)


I think what you are seeing is the redim statement you are setting the total number of items in the array, hence all you need to do is redim the array the size that you want, no need to do math, remembering that an array is 0 based which means that setting an array size of 51 with the redim statement will actually have 52 records. This is a quick little test to show what I mean.

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

or you can use Array.Resize as VisualVincent suggested

Array.Resize(accelrates, 51)

In looking a little further, it appears your For Each statement isn't working as you expect. I would change it to a For statement something like this.

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