Home
VB.NET
Array Flatten Function
Updated Dec 11, 2023
Dot Net Perls
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
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.
For
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
ELEMENT: 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.
This page was last updated on Dec 11, 2023 (new).
Home
Changes
© 2007-2025 Sam Allen