C# 将 1D 数组拆分为每个第 N 个值的 2D 数组

标签 c# arrays .net winforms

我有一个一维整数数组:

int[] array = { 10, 11, 12, 13, 14, 20, 21, 22, 23, 24, 30, 31, 32,33, 34,40,41,42,43, 44};

我想将这个一维数组分成 4 行 5 列的二维数组,其中前 5 个值进入第 1 行,接下来的 5 个值进入第 2 行,依此类推。最终结果应该是这样的:

二维数组:

[[10, 11, 12, 13, 14]
[20, 21, 22, 23, 24]
[30, 31, 32, 33, 34]
[40, 41, 42, 43, 44]]

实际上数组会更长(可能超过 100 行),但是列数是 5,行数可以被 5 整除。例如我已经简化了。到目前为止,这是我尝试过的:

int[] array = { 10, 11, 12, 13, 14, 20, 21, 22, 23, 24, 30, 31, 32,33, 34,40,41,42,43, 44};
int[,] array2D = new int[(array.Length/5),5];

int count_0 = 1;
int count_1 = 1;
int count_2 = 1;
int count_3 = 1;
int count_4 = 1;

for (int i = 0; i < array.Length; i++)
{
    if (i < 5)
    {
        // works for the first 5 values: 
        array2D[0, i] = array[i];
    }
    // I tried this approach for the rest where I try to say that if Im at index 5, 
    //and every 5th element from here, append to it to index[i,0] of array2D and so on. 
    // This do not work, and is what I need help with.
    else if (i >= 5 && i % 5 == 0)
    {
        array2D[count_0, 0] = array[i];
        count_0++;
    }
    else if (i >= 6 && i % 5 == 0)
    {
        array2D[count_1, 1] = array[i];
        count_1++;
    }

    else if (i >= 7 && i % 5 == 0)
    {
        array2D[count_2, 2] = array[i];
        count_2++;
    }

    else if (i >= 8 && i % 5 == 0)
    {
        array2D[count_3, 3] = array[i];
        count_3++;
    }
    else if (i >= 9 && i % 5 == 0)
    {
        array2D[count_4, 4] = array[i];
        count_4++;
    }
}

当然对于这个例子我可以说if > 5 && <10 {append to array2D}if > 10 && <15 {append to array2D}等等,但我想要一些适用于大量数百个值的东西。如果有人有更聪明的方法来做到这一点,请告诉我。

感谢您的帮助!

最佳答案

你可以只计算索引:

for(int i=0;i<array.Length;i++)
    array2D[i/5, i%5] = array[i];

关于C# 将 1D 数组拆分为每个第 N 个值的 2D 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52444323/

相关文章:

c# - 我使用分组查询来获得所需的输出

c# - DotNetNuke:Dnn cdn 更改用于本地 Intranet 执行

c# - 如何使用 selenium webdriver C# 获取元素的样式属性值

php - in_array() 期望参数 2 为数组,Classipress 中给出的字符串

c# - 根据前缀将整数字符串解析为十进制、八进制或十六进制

c# - 在 UWP 应用程序中处理 Dispatcher 异常

javascript - 使用javascript对数组元素进行排序

php - 数组 : How to put value in array index?

.net - Entity Framework 架构中的有界 (Db) 上下文

.net - 如何调试程序集加载 - ConfigurationErrorsException