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.
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 Module
ELEMENT: 10
ELEMENT: 20
ELEMENT: 30
ELEMENT: 40
ELEMENT: 50
ELEMENT: 60