如何数组列表转换成一个多维数组 [英] How to convert list of arrays into a multidimensional array
问题描述
我需要把下面集合转换为双[,]:
I need to convert the following collection into double[,]:
var ret = new List<double[]>();
列表中的所有阵列具有相同的长度。最简单的方法, ret.ToArray()
,产生双重[] [],这不是我想要的。当然,我可以手动创建一个新的数组,并在循环中拷贝数,但有一个更优雅的方式?
All the arrays in the list have the same length. The simplest approach, ret.ToArray()
, produces double[][], which is not what I want. Of course, I can create a new array manually, and copy numbers over in a loop, but is there a more elegant way?
编辑:我的图书馆是从不同的语言,数学,未在.net开发调用。我不认为语言可以利用交错数组。我必须返回一个多维数组。
my library is invoked from a different language, Mathematica, which has not been developed in .Net. I don't think that language can utilize jagged arrays. I do have to return a multidimensional array.
推荐答案
我不相信有什么内置的框架来做到这一点 - 即使 Array.Copy
失败在这种情况下。然而,很容易写code。通过循环做到这一点:
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;
}
}
这篇关于如何数组列表转换成一个多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!