4

I want to assign values to array1,array2,array3.......upto array60.right now i am using following code as i don't know how do do it in one loop ,is there any way to change array name in loop.How to do this in one loop?

            while (array[p] != " ")
            {
                array1[p1] = array[p];
                p++;
                p1++;

            }

            while (array[p] != " ")
            {
                array2[p2] = array[p];
                p++;
                p2++;
            }

            while (array[p] != " ")
            {
                array3[p3] = array[p];
                p++;
                p3++;
            }

            while (array[p] != " ")
            {
                array4[p4] = array[p];
                p++;
                p4++;
            } 
2
  • 4
    Put your arrays into an array. Commented Jun 10, 2016 at 7:18
  • thank you for your reply @Tom but how do i do indexing of that array,i have total 60 string arrays Commented Jun 10, 2016 at 7:31

3 Answers 3

3

with a 2 dimentional array you can use 2 loops to fill your arrays:

int[,] arrays = new int[60,100];
for(int arraynumber = 0; arraynumber < 60; arraynumber++)
{
    for(int i = 0; i< 100;i++)
    {
        arrays[arraynumber,i] = arrays[0,i];
    }
}

you can also use an array of arrays

Sign up to request clarification or add additional context in comments.

6 Comments

I doubt if 2D array int[,] arrays is a good choice here. What if arrays in the question are of different lengths? Jugged array int[][] arrays looks far better.
you should use an array of arrays if the arrays don't have the same size
I'm not shure, but I think an array of arrays is slower than a 2d array, but I'm realy not shure
All arrays have same length,i will try your solution @Thomas
I have no IDE here @ the moment, so maybe there is a sintaxerror
|
1

Try this

var sourceArray = new string[]{"1","2","3","4","5","6"};
var destArrays = new string[4,sourceArray.Length];
int innerIndex = 0;
int outerIndex = 0;

while(outerIndex<destArrays.GetLength(0))
{
    while (innerIndex<sourceArray.Length && sourceArray[innerIndex] != " ")
  {
      destArrays[outerIndex,innerIndex] = sourceArray[innerIndex];
      innerIndex++;
  }
  innerIndex = 0;
  outerIndex++;
}

Comments

0

A simple solution:

string[][] arrays = new string[][] { array1, array2, array3 };

foreach (string[] arr in arrays) {
    // do staff here
}

2 Comments

i did't get your code ,how do i change name from array1 to array2 to assign values to arrays
You don't change it. You list all the arrays in the { } brackets and the outer forech loop goes through all the array you have listed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.