如何在C#中将2D字符数组拆分为较小的数组?

我有一个二维字符数组,我想将其拆分为较小的数组。 2d数组为4 * 4,我想将此2d数组拆分为4个不同的数组。所有数组都有四个元素。

- For example I have this 2d array:
     1 2 5 6
     3 4 7 8
     4 4 4 7
     4 4 5 1
- And i want cut it for this arrays:
  [1,2,3,4] [5,6,7,8] [4,4,4] [4,5,1]
qiuyue00 回答:如何在C#中将2D字符数组拆分为较小的数组?

天真的方法是遍历元素。

    static void Main(string[] args)
    {
        var matrix = new int[,] { 
            { 1,2,5,6 },{ 3,4,7,8 },{ 4,7 },1 }
        };

        var array11 = matrix.GetSubMatrixElements(0,2);
        // [1,3,4]
        var array12 = matrix.GetSubMatrixElements(0,2);
        // [5,6,8]
        var array21 = matrix.GetSubMatrixElements(2,2);
        // [4,4]
        var array22 = matrix.GetSubMatrixElements(2,1]
    }

    public static T[] GetSubMatrixElements<T>(this T[,] matrix,int startRow,int startCol,int rowCount,int colCount)
    {
        var array = new T[rowCount*colCount];

        int index = 0;
        for (int i = startRow; i < startRow+rowCount; i++)
        {
            for (int j = startCol; j < startCol+colCount; j++)
            {
                array[index++] = matrix[i,j];
            }
        }

        return array;
    }

如果想要更快的结果,可以使用Buffer.BlockCopy()代替内部循环。

    public static T[] GetSubMatrixElements<T>(this T[,int colCount)
    {
        int n = matrix.GetLength(0),m = matrix.GetLength(1);
        var array = new T[rowCount*colCount];
        int u = Buffer.ByteLength(matrix)/(n*m);
        int index = 0;
        for (int i = startRow; i < startRow+rowCount; i++)
        {
            Buffer.BlockCopy(matrix,u*(i*m+startCol),array,u*index,u*colCount);
            index += colCount;
        }
        return array;
    }
本文链接:https://www.f2er.com/3165681.html

大家都在问