Array Flatten FunctionConvert a 2D array into a 1D array with a nested For loop, ensuring all the elements are still present.
This page was last reviewed on Dec 11, 2023.
Flatten array. It can be difficult to use 2D arrays in VB.NET programs. Sometimes it is helpful to flatten these arrays into 1D arrays.
2D Array
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.
Array Length
Step 2 We allocate our 1D array that will hold all the elements from the original 2D array.
Step 3 We call GetUpperBound on the 2D array with arguments of 0 and 1—these are the ranks (dimensions) of the array. We use nested For-loops.
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 Module
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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Dec 11, 2023 (new).
© 2007-2024 Sam Allen.