You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将三维数组的首个索引部分复制到二维数组?

在C#中提取三维数组的首个索引部分到二维数组

C# 里确实没有像 PHP 那样直接通过 array3d[0,,] 提取三维数组切片的语法,得手动处理元素复制,下面是几种可行的方案:

  • 手动嵌套循环赋值
    这是最直接的方式,适合固定大小的数组:

    string[,] array2d = new string[9, 9];
    // 遍历二维数组的每个位置,从三维数组的首个索引层取值
    for (int i = 0; i < array2d.GetLength(0); i++)
    {
        for (int j = 0; j < array2d.GetLength(1); j++)
        {
            array2d[i, j] = array3d[0, i, j];
        }
    }
    
  • 封装成扩展方法复用
    如果需要多次做这种操作,可以写个通用扩展方法,让代码更简洁:

    public static class ArrayExtensions
    {
        public static T[,] Get2DSliceFrom3D<T>(this T[,,] array3d, int firstIndex)
        {
            int rowCount = array3d.GetLength(1);
            int colCount = array3d.GetLength(2);
            T[,] result = new T[rowCount, colCount];
            
            for (int i = 0; i < rowCount; i++)
            {
                for (int j = 0; j < colCount; j++)
                {
                    result[i, j] = array3d[firstIndex, i, j];
                }
            }
            
            return result;
        }
    }
    
    // 调用方式
    string[,] array2d = array3d.Get2DSliceFrom3D(0);
    
  • 用LINQ简化(需转换为交错数组再处理)
    如果想少写循环,可以借助LINQ先把切片转成交错数组,再转成矩形数组:

    using System.Linq;
    
    var jaggedSlice = Enumerable.Range(0, array3d.GetLength(1))
                                .Select(i => Enumerable.Range(0, array3d.GetLength(2))
                                                       .Select(j => array3d[0, i, j])
                                                       .ToArray())
                                .ToArray();
    
    // 转成矩形数组
    string[,] array2d = new string[9, 9];
    for (int i = 0; i < jaggedSlice.Length; i++)
    {
        for (int j = 0; j < jaggedSlice[i].Length; j++)
        {
            array2d[i, j] = jaggedSlice[i][j];
        }
    }
    

补充说明:C#的矩形数组([,])是连续内存存储的结构,和PHP动态数组的底层实现不同,所以无法直接通过索引切片完成内存块的直接映射,必须逐个元素复制。

内容的提问来源于stack exchange,提问作者Tom.Wennemers

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 05:25:07