How to loop through multiple arrays?
Question
I'm new to this, so sorry if my question has been asked before. I have searched but have not been able to find, or perhaps recognise, an answer. I am using visual studio 2008 and creating an app in vb.net.
I have 4 arrays named:- account1 account2 account3 account4. They all have 4 elements. I want to assign values to the elements in the arrays in an efficient manner. I thought two for next loops would do it. My pseudo code looks something like this
for i=1 to 4
for c= 0 to 3
account(i)(c)= 'mydata' /so account(i) would be account1 etc and c the element
next c
next i
and thus all the elements of all the arrays are populated without me having to set up a fornext loop for each individual array name. How can I achieve this please.
Hope I have provided enough info to be of use, and that you can help. Thanks for all and any advice.
Solution
If I understand correctly, why not:
For i as integer = 0 to 3
account1(i) = "Account1"
account2(i) = "Account2"
account3(i) = "Account3"
account4(i) = "Account4"
Next
Edit VB.Net for Qua's answer:
dim accounts(4,4) as integer
for i as integer = 0 To accounts.GetUpperBound(0)
for j as integer = 0 To accounts.GetUpperBound(1)
accounts(i, j) = new integer 'not needed for intergers, but if you had a class in here'
accounts(i, j) = i*j;
next
next
OTHER TIPS
You should create a multidimensional array instead of 4 arrays, that would allow you to loop genericly through the arrays.
int[,] accounts = new int[4,4] // 4 accounts with 4 elements
for (int i = 0 ; i < accounts.GetUpperBound(0); i++)
for (int j = 0 ; i < accounts.GetUpperBound(1); j++)
accounts[i,j] = i*j;
next
next
As I read your code example, I don't think that you need to use 2 seperate loops, as if I'm right you are assigning the same value to the ith position of your array eg:
array1(i) = array2(i) = array3(i) = array4(i)
In your example above you could write something like this (in pseudocode):
for i = 0 to 3
account1(i) = MyData
account2(i) = MyData
account3(i) = MyData
account4(i) = MyData
next i
I think that this is clearer than trying to write a loop for the variable names, especially for the number of arrays you are maintaining
Another option, which might be more appropriate if you have lots of arrays, would be to maintain a list of arrays which can then be iterated through simply enough.
PseudoCode for this option:
for each array in listOfArrays
for i = 0 to 3
array(i) = MyData
next i
next
This is definitely clearer than trying to generate the names of the arrays dynamically, and more maintainable as well