2D Arrays

rbulph

Junior Contributor
Joined
Feb 17, 2003
Messages
397
Is there a simple way to re-order the data in a 2D array by rows? e.g. in an array declared as "s(3,3) as string", move all the items with the first index as 0 to the end, and shunt the other items up on level as regards the first index.
 
Have you considered using jagged arrays? With jagged arrays you can treat different "rows" (if that is how you prefer to think of it) independently. For example...
Code:
[Color=Blue]Private Sub [/Color]Button1_Click([Color=Blue]ByVal [/Color]sender [Color=Blue]As [/Color]System.Object, _
    [Color=Blue]ByVal [/Color]e [Color=Blue]As [/Color]System.EventArgs) [Color=Blue]Handles [/Color]Button1.Click
   [Color=Green] 'Create empty array that can hold 3 rows
[/Color]    [Color=Blue]Dim [/Color]Test [Color=Blue]As [/Color]String()() = [Color=Blue]New [/Color]String(2)() {}
 
[Color=Green]    'Create and populate rows.[/Color]
    [Color=Blue]For [/Color]i [Color=Blue]As Integer [/Color]= 0 [Color=Blue]To[/Color] 2
        Test(i) = [Color=Blue]New [/Color]String(2) {} [Color=Green]'Create a row with 3 items[/Color]
 [Color=Green]
        'Populate row[/Color]
        [Color=Blue]For [/Color]j [Color=Blue]As Integer [/Color]= 0 [Color=Blue]To [/Color]2
            Test(i)(j) = Chr(65 + j + i * 3)[Color=Green] 'Set a single, unique character.[/Color][Color=Blue]
        Next
    Next[/Color]
 
    OutputArray(Test)
    MessageBox.Show("Click OK to swap")
 
   [Color=Green] 'Swap two rows
[/Color]    [Color=Blue]Dim [/Color]placeholder [Color=Blue]As [/Color]String() = Test(1)
    Test(1) = Test(0)
    Test(0) = placeholder
 
   OutputArray(Test)
[Color=Blue]End Sub[/Color]
 
[Color=Blue]Sub [/Color]OutputArray([Color=Blue]ByVal [/Color]data [Color=Blue]As [/Color]String()())
    txtOutput.Clear()
    [Color=Blue]For [/Color]i [Color=Blue]As Integer [/Color]= 0 [Color=Blue]To [/Color]UBound(data)
        [Color=Blue]For [/Color]j [Color=Blue]As Integer [/Color]= 0 [Color=Blue]To [/Color]UBound(data(i))
            txtOutput.Text &= data(i)(j) & "; "
        [Color=Blue]Next[/Color]
        txtOutput.Text &= Environment.NewLine
[Color=Blue]    Next
End Sub[/Color]

Another option might be to use Array.Copy to copy data from one row to another, provided that there is a relevant overload present. This would also require a second 1-D array to act a buffer.
 
Thanks, that's useful. I wasn't aware of the possibility of doing this. Ideally I'd like to have the facility to rearrange both rows and columns, but I don't think there's a structure that will allow me to do this. Perhaps I will just have to reposition items one by one on one axis.
 
Back
Top