这是完全错误的。你不能b
那样做。甚至初始化都是错误的。在 .NET 中有两种类型的多维数组......真正的多维数组和锯齿状数组......
让我们开始吧...您正在使用锯齿状数组(我不会告诉您它是什么或区别,您没有要求它...如果您需要它们,请在谷歌上搜索)
int[][] a = new int[10][]; // see how you define it?
// Only the first dimension can be is sized here.
for (int i = 0; i < a.Length; i++)
{
// For each element, create a subarray
// (each element is a row in a 2d array, so this is a row of 10 columns)
a[i] = new int[10];
}
现在您已经定义了一个 10x10 数组锯齿状数组。
现在有点LINQ:
你想要一个列表:
List<List<int>> b = a.Select(row => row.ToList()).ToList();
你想要一个数组:
int[][] c = b.Select(row => row.ToArray()).ToArray();
第一个表达式的意思
foreach element of a, we call this element row `a.Select(row =>` <br>
make of this element a List `row.ToList()` and return it<br>
of all the results of all the elements of a, make a List `.ToList();`
第二个是镜面。
现在......只是出于好奇,如果你有一个真正的多维数组?然后它很复杂,非常复杂。
int[,] a = new int[10,10];
int l0 = a.GetLength(0);
int l1 = a.GetLength(1);
var b = new List<List<int>>(
Enumerable.Range(0, l0)
.Select(p => new List<int>(
Enumerable.Range(0, l1)
.Select(q => a[p, q]))));
var c = new int[b.Count, b[0].Count];
for (int i = 0; i < b.Count; i++)
{
for (int j = 0; j < b[i].Count; j++)
{
c[i, j] = b[i][j];
}
}
使用一个棘手(和可怕)的 LINQ 表达式,我们可以将多维数组“转换”为List<List<int>>
. 使用 LINQ 后路并不容易实现(除非你想使用List<T>.ForEach()
你不应该使用的,因为它不是 kosher,然后List<T>.ForEach()
不是 LINQ)......但它很容易用两个嵌套的for ()