转换列表< T>到阵列(多维) [英] Converting List<T> to Array (multidimensional)
问题描述
可能重复:
如何转换列表<>到多维数组?
Possible Duplicate:
How can I convert a list<> to a multi-dimensional array?
我想为此使用double[,]
形式的数组,因为我不知道该数组的长度是什么,我想先制作一个List
,然后再使用List<T>.ToArray()
转换为double[,]
:
I want to have an array in form of double[,]
for this purpose since I do not know what will be the length of this array, I want to make a List
first then later using List<T>.ToArray()
convert it to double[,]
:
public double[,] FilterClampedData(double[,] data)
{
var finalData = new List<double[]>();
//Do some stuff on parameter
return finalData.ToArray(); ///Does not compile :(
}
推荐答案
由于ToArray
返回一维数组,因此也难怪为什么不编译.如果返回double[][]
,它将编译.您还可以通过两个嵌套循环手动构建二维数组:
Since ToArray
returns a one-dimensional array, there is no wonder why this does not compile. If you were returning double[][]
, it would compile, however. You could also build your 2-D array manually with two nested loops:
var R = finalData.Count;
var C = finalData[0].Length;
var res = new double[R, C];
for (int r = 0 ; r != R ; r++)
for (int c = 0 ; c != C ; c++)
res[r, c] = finalData[r][c];
return res;
上面的代码假定finalData
中至少有一项,并且finalData
中所有列表的长度是相同的.
The code above assumes that you have at least one item in the finalData
, and that the length of all lists inside finalData
is the same.
这篇关于转换列表< T>到阵列(多维)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!