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

   2024-09-30 3770
核心提示:在C#中,没有像Python那样直接的多维数组切片语法using System;class Program{static void Main(){// 创建一个 4x4 的二维整数数

在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变量来改变切片的位置和大小。注意,这个示例仅适用于矩形(二维)数组。对于更高维度的数组,你需要使用类似的方法,但需要添加更多的循环和变量来处理额外的维度。

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号