C# Creating an array of arrays

前端 未结 4 1903
终归单人心
终归单人心 2020-11-30 07:33

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 i         


        
相关标签:
4条回答
  • 2020-11-30 07:37

    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
        }
    }
    
    0 讨论(0)
  • 2020-11-30 07:41

    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...};
    
    0 讨论(0)
  • 2020-11-30 07:43

    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};
    
    0 讨论(0)
  • 2020-11-30 07:48

    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.

    0 讨论(0)
提交回复
热议问题