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

时间:2018-09-21 12:58:18

标签: 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};

我想将此1D数组划分为4行5列的2D数组,其中前5个值进入第1行,接下来的5个进入第2行,依此类推。最终结果应如下所示:

array2D:

[[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}等等,但是我想要适用于大量数百个值的东西。如果有人有更聪明的方法来进行此操作,请告诉我。

谢谢您的帮助!

3 个答案:

答案 0 :(得分:8)

您可以只计算索引:

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

答案 1 :(得分:3)

您可以使用Enumerable.GroupBy使用LINQ来完成。

array.GroupBy(x => x / 5)
   .Select(x => x.ToArray())
   .ToArray()

答案 2 :(得分:3)

您可以使用简单的除法轻松地计算索引。通过将i除以所需的列号来计算该行。专栏只是提醒人们该分裂。

using System;

public class Program
{
    public static T[,] SplitInto2DArray<T>(T[] array, int rows, int columns) {      
        T[,] result = new T[rows, columns];

        for (int i = 0; i < array.Length; i++) {
            result[i / columns, i % columns] = array[i];    
        }

        return result;
    }

    public static void PrintArray<T>(T[,] array) {
        for (int i = 0; i < array.GetLength(0); i++) {
            for (int j = 0; j < array.GetLength(1); j++) {
                Console.Write(array[i, j] + " ");
            }
            Console.WriteLine();
        }
    }

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

        int[,] splittedArray = SplitInto2DArray(array, 4, 5);

        PrintArray(splittedArray);
    }
}