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

如何在C#中转置动态大小与动态类型的二维ArrayList?

Python转置函数的C#实现(基于嵌套ArrayList)

原Python代码功能说明

原Python代码实现了二维网格的转置操作,核心逻辑是:

  • 取所有行中最短的长度作为转置后的列数,避免索引越界
  • 遍历每一列索引,收集原网格中所有行对应列的元素,组成转置后的行

C#实现代码

using System.Collections;

public class GridTransposer
{
    public ArrayList Transpose(ArrayList gridMap)
    {
        // 处理空输入
        if (gridMap == null || gridMap.Count == 0)
            return new ArrayList();

        // 计算所有子列表的最小长度(兼容ulong维度上限)
        ulong minRowLength = ulong.MaxValue;
        foreach (ArrayList row in gridMap)
        {
            if (row == null)
            {
                minRowLength = 0;
                break;
            }
            ulong currentRowLength = (ulong)row.Count;
            if (currentRowLength < minRowLength)
                minRowLength = currentRowLength;
        }

        ArrayList transposedGrid = new ArrayList();

        // 生成转置后的网格
        for (ulong colIndex = 0; colIndex < minRowLength; colIndex++)
        {
            ArrayList newRow = new ArrayList();
            foreach (ArrayList row in gridMap)
            {
                // 由于已取最小长度,此处可安全访问对应索引
                newRow.Add(row[(int)colIndex]);
            }
            transposedGrid.Add(newRow);
        }

        return transposedGrid;
    }
}

关键实现细节

  • 维度兼容性:使用ulong类型处理长度和索引,满足x/y维度上限为ulong.MaxValue的要求
  • 类型存储:嵌套ArrayList天然支持存储任意类型元素(可直接作为dynamic使用),符合多类型存储需求
  • 异常防护:提前处理空输入、空行的情况,避免运行时异常
  • 逻辑对齐:完全复刻原Python的转置逻辑,仅取所有行的最短长度作为转置后的有效列数

内容的提问来源于stack exchange,提问作者Red Mermaid

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 23:50:24