调整大小和初始化二维数组C#

调整大小和初始化二维数组C#

问题描述:

我有一个类型为string的2D数组,我想在某些循环内修改和调整大小。我的主要目标是通过创建一个2d数组来使用最小内存,该数组将在循环的每次迭代中进行修改,并将char添加到此数组中的适当单元格。这里是我的代码:调整大小和初始化二维数组C#

static void Main(string[] args) 
    { 
     int maxBound = 100;//length of freq array 
     Random rnd1 = new Random(); 
     int numLoops = rnd1.Next(1000, 1200);//number of total elements in freq array 
     int[] freq = new int[maxBound];//freq array 
     string[,] _2dim = new string[maxBound, numLoops];//rows,columns 
     Random rnd2 = new Random(); 

     for (int i = 0; i < numLoops; i++) 
     { 
      int s = rnd2.Next(maxBound); 
      freq[s]++; 
      //Here I try to add `*` to the _2dim array while resizing it to the appropriate size 

     } 
    } 

什么是解决方案的主要途径?谢谢

+1

1.您无法调整数组的大小2.使用两个for循环遍历所有元素 –

+0

我可以使用而不是像列表列表? – axcelenator

+1

是的绝对 - 我认为这是你应该使用的方法 –

相反,你可能想使用一个锯齿状的一个二维数组。简而言之,二维数组总是一个N×M的矩阵,你不能调整大小,而一个锯齿形数组是一个数组的阵列,你可以单独初始化每个内部元素的不同大小(详见here

int maxBound = 100; 
Random rnd = new Random(); 
int numLoops = rnd.Next(1000, 1200); 

string[][] jagged = new string[numLoops][]; 

for (int i = 0; i < numLoops; i++) 
{ 
    int currLen = rnd.Next(maxBound); 
    jagged[i] = new string[currLen]; 

    for (int j = 0; j < currLen; j++) 
     jagged[i][j] = "*"; // do some initialization 
} 

您应该使用嵌套在列表中的类型为string的列表。然后你可以修改这个列表。为了遍历这个,你应该使用两个for循环。

List<List<string>> l = new List<List<string>> { new List<string> { "a", "b" }, new List<string> { "1", "2" } }; 

迭代例如:

for(int i = 0; i < l.Count; i++) 
     { 
      for(int j = 0; j < l[i].Count; j++) 
      { 
       Console.WriteLine(l[i][j]); 
      } 
     }