我想搜索会给我一个关于2D列表到2D数组的成功机会,但它似乎没有我想象的那么常见。
这就是我得到的:
// init array
int[][] a = new int[10][10];
// change 2D array to 2D list
List<List<int>> b = a.Cast<List<int>>().ToList();
// change 2D list back to 2D array
???
如何将b更改为2D数组?上述说法也是正确的吗?
发布于 2013-08-13 18:47:42
就像这样:
List<List<int>> lists = arrays.Select(inner=>inner.ToList()).ToList();
int[][] arrays = lists.Select(inner=>inner.ToArray()).ToArray();
发布于 2013-08-13 18:59:47
这是完全错误的。你不能用那种方式让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()
,你永远不应该使用,因为它不犹太,然后List<T>.ForEach()
不是LINQ).但是使用两个嵌套的for ()
很容易做到
https://stackoverflow.com/questions/18216775
复制相似问题