且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将数组列表转换为多维数组

更新时间:2023-02-14 12:47:15

我不相信框架中内置了任何东西可以做到这一点 - 即使 Array.Copy 在这种情况下也失败了.但是,通过循环编写代码很容易:

I don't believe there's anything built into the framework to do this - even Array.Copy fails in this case. However, it's easy to write the code to do it by looping:

using System;
using System.Collections.Generic;

class Test
{
    static void Main()
    {
        List<int[]> list = new List<int[]>
        {
            new[] { 1, 2, 3 },
            new[] { 4, 5, 6 },
        };

        int[,] array = CreateRectangularArray(list);
        foreach (int x in array)
        {
            Console.WriteLine(x); // 1, 2, 3, 4, 5, 6
        }
        Console.WriteLine(array[1, 2]); // 6
    }

    static T[,] CreateRectangularArray<T>(IList<T[]> arrays)
    {
        // TODO: Validation and special-casing for arrays.Count == 0
        int minorLength = arrays[0].Length;
        T[,] ret = new T[arrays.Count, minorLength];
        for (int i = 0; i < arrays.Count; i++)
        {
            var array = arrays[i];
            if (array.Length != minorLength)
            {
                throw new ArgumentException
                    ("All arrays must be the same length");
            }
            for (int j = 0; j < minorLength; j++)
            {
                ret[i, j] = array[j];
            }
        }
        return ret;
    }

}