C# Creating an array of arrays

C#Arrays

C# Problem Overview


I'm trying to create an array of arrays that will be using repeated data, something like below:

int[] list1 = new int[4] { 1, 2, 3, 4 };
int[] list2 = new int[4] { 5, 6, 7, 8 };
int[] list3 = new int[4] { 1, 3, 2, 1 };
int[] list4 = new int[4] { 5, 4, 3, 2 };

int[,] lists = new int[4, 4] {  list1 ,  list2 ,  list3 ,  list4  };

I can't get it to work and so I'm wondering if I'm approaching this wrong.

What I'm attempting to do is create some sort of method to create a long list of the values so I can process them in a specific order, repeatedly. Something like,

int[,] lists = new int[90,4] { list1, list1, list3, list1, list2, (and so on)};

for (int i = 0; i < 90; ++i) {
   doStuff(lists[i]);
}

and have the arrays passed to doStuff() in order. Am I going about this entirely wrong, or am I missing something for creating the array of arrays?

C# Solutions


Solution 1 - C#

What you need to do is this:

int[] list1 = new int[4] { 1, 2, 3, 4};
int[] list2 = new int[4] { 5, 6, 7, 8};
int[] list3 = new int[4] { 1, 3, 2, 1 };
int[] list4 = new int[4] { 5, 4, 3, 2 };

int[][] lists = new int[][] {  list1 ,  list2 ,  list3 ,  list4  };

Another alternative would be to create a List<int[]> type:

List<int[]> data=new List<int[]>(){list1,list2,list3,list4};

Solution 2 - C#

The problem is that you are attempting to define the elements in lists to multiple lists (not multiple ints as is defined). You should be defining lists like this.

int[,] list = new int[4,4] {
 {1,2,3,4},
 {5,6,7,8},
 {1,3,2,1},
 {5,4,3,2}};

You could also do

int[] list1 = new int[4] { 1, 2, 3, 4};
int[] list2 = new int[4] { 5, 6, 7, 8};
int[] list3 = new int[4] { 1, 3, 2, 1 };
int[] list4 = new int[4] { 5, 4, 3, 2 };

int[,] lists = new int[4,4] {
 {list1[0],list1[1],list1[2],list1[3]},
 {list2[0],list2[1],list2[2],list2[3]},
 etc...};

Solution 3 - C#

I think you may be looking for Jagged Arrays, which are different from multi-dimensional arrays (as you are using in your example) in C#. Converting the arrays in your declarations to jagged arrays should make it work. However, you'll still need to use two loops to iterate over all the items in the 2D jagged array.

Solution 4 - C#

This loops vertically but might work for you.

int rtn = 0;    
foreach(int[] L in lists){
    for(int i = 0; i<L.Length;i++){
          rtn = L[i];
      //Do something with rtn
    }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionFidsahView Question on Stackoverflow
Solution 1 - C#SeanView Answer on Stackoverflow
Solution 2 - C#SurootView Answer on Stackoverflow
Solution 3 - C#NoldorinView Answer on Stackoverflow
Solution 4 - C#Robert QuinnView Answer on Stackoverflow