By looping over all the values in the upper bounds of the array for each rank, we can copy elements to a 1D array. In VB.NET this can be done with nested For To loops and GetUpperBound.
Example. In the Main subroutine, we create a 2D array with 2 rows and 3 columns. Our goal is to convert this to a flattened array of 6 elements.
Step 1 In Flatten() we need to determine the total element count. If the Length is 0, we just return an empty array.
Step 4 We now have a 1D array containing all the elements of the original 2D array, just without the second dimension.
Module Module1
Function Flatten(input As Integer(,)) as Integer()
' Step 1: if zero elements, return an empty array.
If input.Length = 0
Return {}
End If
' Step 2: get total element count, and allocate the 1D array.
Dim resultInteger(input.Length - 1) As Integer
' Step 3: use nested For-loops with GetUpperBound to copy all elements.
Dim write = 0
For i = 0 To input.GetUpperBound(0)
For z = 0 To input.GetUpperBound(1)
resultInteger(write) = input(i, z)
write += 1
Next
Next
' Step 4: return the 1D array.
Return resultInteger
End Function
Sub Main()
Dim elements = { { 10, 20, 30 }, { 40, 50, 60 } }
' Call Flatten.
Dim result = Flatten(elements)
For Each value in result
Console.WriteLine("ELEMENT: {0}", value)
Next
End Sub
End ModuleELEMENT: 10
ELEMENT: 20
ELEMENT: 30
ELEMENT: 40
ELEMENT: 50
ELEMENT: 60
Sometimes the dimensions of a 2D array are not useful—the values themselves may be the important part. We could still average the elements, for example.
In this case, flattening the array is worthwhile. Other Functions in the VB.NET program may be better able to deal with the flattened one-dimensional array.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.