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

Arn*_*und 17 c# linq jagged-arrays multidimensional-array

我需要将以下集合转换为double [,]:

 var ret = new List<double[]>();
Run Code Online (Sandbox Code Playgroud)

列表中的所有数组都具有相同的长度.最简单的方法,ret.ToArray()产生double [] [],这不是我想要的.当然,我可以手动创建一个新数组,并在循环中复制数字,但是有更优雅的方式吗?

编辑:我的库是从另一种语言Mathematica调用的,该语言尚未在.Net中开发.我不认为该语言可以利用锯齿状数组.我必须返回一个多维数组.

Jon*_*eet 25

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

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;
    }

}
Run Code Online (Sandbox Code Playgroud)


Jod*_*ell 5

如果你要复制(我想不出更好的方法)

var width = ret[0].length;
var length = ret.Count;
var newResult = new double[width, length]
Buffer.BlockCopy(ret.SelectMany(r => r).ToArray(),
                    0, 
                    newResult, 
                    0, 
                    length * width);
return newResult;
Run Code Online (Sandbox Code Playgroud)

编辑

我几乎可以肯定循环比使用SelectManyandToArray更快。

我知道我什么时候被扫射了。


Mar*_*cin 5

您可以执行以下扩展名:

    /// <summary>
    /// Conerts source to 2D array.
    /// </summary>
    /// <typeparam name="T">
    /// The type of item that must exist in the source.
    /// </typeparam>
    /// <param name="source">
    /// The source to convert.
    /// </param>
    /// <exception cref="ArgumentNullException">
    /// Thrown if source is null.
    /// </exception>
    /// <returns>
    /// The 2D array of source items.
    /// </returns>
    public static T[,] To2DArray<T>(this IList<IList<T>> source)
    {
        if (source == null)
        {
            throw new ArgumentNullException("source");
        }

        int max = source.Select(l => l).Max(l => l.Count());

        var result = new T[source.Count, max];

        for (int i = 0; i < source.Count; i++)
        {
            for (int j = 0; j < source[i].Count(); j++)
            {
                result[i, j] = source[i][j];
            }
        }

        return result;
    }
Run Code Online (Sandbox Code Playgroud)

  • 不,这是正常的方法 (2认同)

Eth*_*own 5

没有简单的方法可以做到这一点,因为在你描述的情况下,没有什么能阻止double[]列表中的数组不同的大小,这与二维矩形数组不兼容.但是,如果您能够保证double[]数组都具有相同的维度,则可以按如下方式构建二维数组:

var arr = new double[ret.Count(),ret[0].Count()];

for( int i=0; i<ret.Count(); i++ ) {
  for( int j=0; j<ret[i].Count(); j++ )
    arr[i,j] = ret[i][j];
}
Run Code Online (Sandbox Code Playgroud)

如果double[]列表中的任何数组比第一个数组短,则会产生运行时错误,如果任何数组大于第一个数组,则会丢失数据.

如果您确实要将锯齿状阵列存储在矩形阵列中,则可以使用"魔术"值来表示该位置没有值.例如:

var arr = new double[ret.Count(),ret.Max(x=>x.Count())];

for( int i=0; i<ret.Count(); i++ ) {
  for( int j=0; j<arr.GetLength(1); j++ )
    arr[i,j] = j<ret[i].Count() ? ret[i][j] : Double.NaN;
}
Run Code Online (Sandbox Code Playgroud)

在编辑上,我认为这是一个非常糟糕的想法™; 当你去使用矩形阵列时,你必须一直检查Double.NaN.此外,如果您想Double.NaN在数组中使用合法值,该怎么办?如果你有一个锯齿状阵列,你应该把它留作锯齿状阵列.