温馨提示×

如何用c#实现多维数组切片

c#
小樊
82
2024-09-06 01:46:59
栏目: 编程语言

在C#中,没有像Python那样直接的多维数组切片语法

using System;

class Program
{
    static void Main()
    {
        // 创建一个 4x4 的二维整数数组
        int[,] array = new int[4, 4] {
            { 1, 2, 3, 4 },
            { 5, 6, 7, 8 },
            { 9, 10, 11, 12 },
            { 13, 14, 15, 16 }
        };

        // 获取数组的行数和列数
        int rowCount = array.GetLength(0);
        int colCount = array.GetLength(1);

        // 定义要切片的起始行和列,以及切片的行数和列数
        int startRow = 1;
        int startCol = 1;
        int sliceRowCount = 2;
        int sliceColCount = 2;

        // 创建一个新的二维数组来存储切片结果
        int[,] slice = new int[sliceRowCount, sliceColCount];

        // 遍历原始数组并将指定切片复制到新数组中
        for (int row = 0; row< sliceRowCount; row++)
        {
            for (int col = 0; col< sliceColCount; col++)
            {
                slice[row, col] = array[startRow + row, startCol + col];
            }
        }

        // 打印切片后的二维数组
        Console.WriteLine("Sliced array:");
        for (int row = 0; row< sliceRowCount; row++)
        {
            for (int col = 0; col< sliceColCount; col++)
            {
                Console.Write(slice[row, col] + " ");
            }
            Console.WriteLine();
        }
    }
}

这个示例从一个4x4的二维整数数组中切出了一个2x2的子数组。你可以根据需要修改startRowstartColsliceRowCountsliceColCount变量来改变切片的位置和大小。注意,这个示例仅适用于矩形(二维)数组。对于更高维度的数组,你需要使用类似的方法,但需要添加更多的循环和变量来处理额外的维度。

0