【问题标题】:How to Use a loop to call up arrays with different names in c#如何在c#中使用循环调用具有不同名称的数组
【发布时间】:2016-10-11 01:31:35
【问题描述】:

我想给array1、array2、array3 赋值......直到array60。现在我正在使用以下代码,因为我不知道如何在一个循环中做到这一点,有什么办法可以在循环中更改数组名称。如何在一个循环中执行此操作?

            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++;
            } 

【问题讨论】:

  • 把你的数组放到一个数组中。
  • 感谢您的回复@Tom,但我如何对该数组进行索引,我总共有 60 个字符串数组

标签: c# arrays loops


【解决方案1】:

使用二维数组,您可以使用 2 个循环来填充数组:

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];
    }
}

你也可以使用数组数组

【讨论】:

  • 我怀疑 2D array int[,] arrays 是否是一个不错的选择。如果问题中的数组具有不同长度怎么办? Jugged 数组 int[][] arrays 看起来要好得多。
  • 如果数组大小不同,则应使用数组数组
  • 我不舒尔,但我认为数组数组比二维数组慢,但我真的不舒尔
  • 所有数组的长度相同,我会试试你的解决方案@Thomas
  • 我现在没有IDE,所以可能有sintaxerror
【解决方案2】:

试试这个

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++;
}

【讨论】:

    【解决方案3】:

    一个简单的解决方案:

    string[][] arrays = new string[][] { array1, array2, array3 };
    
    foreach (string[] arr in arrays) {
        // do staff here
    }
    

    【讨论】:

    • 我没有得到您的代码,如何将名称从 array1 更改为 array2 以将值分配给数组
    • 你不会改变它。您在 { } 括号中列出所有数组,外部 forech 循环遍历您列出的所有数组。
    猜你喜欢
    • 1970-01-01
    • 2017-07-22
    • 2014-09-10
    • 2013-10-20
    • 1970-01-01
    • 2017-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多