在c#中将单维数组转换为2D数组
我有两个1Darrays。 我想将这两个数组转换为单个2D数组。
我的代码是:
public Static void Main() { int[] arrayRow; int[] arrayCol; for (int i = 0; i < row; i++) { for (int j = 0; j < column; j++) { int[,] myArray = new int[row,column]; myArray[i,j] = arrayRow[i]; // not possible -- your suggestions } } for (int i = 0; i < row; i++) { for (int j = 0; j < column; j++) { Console.Write(myArray[i,j]); } } }
我需要在myArray[,]
保存arrayRow[]
和arrayRow[]
myArray[,]
。
例如,
如果我们有arrayRow[]={1,2,3}
和arrayCol[]={4,5,6}
那么myArray [,] = {(1,4),(2,5),(3,6) }
注意: arrayRow
和arrayRow
可能有不同的长度。 在这种情况下,没有对的元素应该存储在新的单维数组result[]
。
没试过这个,我只想猜你要做什么,但这里是:
int[] arrayRow; int[] arrayCol; int[,] myArray = new int[Math.Max(arrayRow.Length, arrayCol.Length), 2]; for (int i = 0; i < arrayRow.Length; i++) myArray[i, 0] = arrayRow[i]; for (int i = 0; i < arrayCol.Length; i++) myArray[i, 1] = arrayCol[i];
你的arrayRow[]
和arrayRow[]
将只是一个二维数组的两行(如果你不是指锯齿状的arrayRow[]
行)。
所以将两个数组合二为一的代码就是:
public static T[,] Union(T[] first, T[] second) //where T : struct { T[,] result = new T[2, Math.Max(first.Length, second.Length)]; int firstArrayLength = first.Length * Marshal.SizeOf(typeof(T)); Buffer.BlockCopy(first, 0, result, 0, firstArrayLength); Buffer.BlockCopy(second, 0, result, firstArrayLength, second.Length * Marshal.SizeOf(typeof(T))); return result; }
正如它已被指导 , BlockCopy
比循环更冷。
如果你的意思是你需要一个锯齿状的数组(比如int[][]
),那么解决方案将更简单:
public static T[][] UnionJagged(T[] first, T[] second) { return new T[2][] { first, second }; }
如果我们添加多个数组作为参数function,哪个转换为更简单:
public static T[][] UnionJagged(params T[][] arrays) { return arrays; } static void Main() { int[] a = new int[] { 10, 2, 3 }; int[] b = new int[] { -1, 2, -3 }; int[] c = new int[] { 1, -2, 3 }; int[][] jaggedThing = UnionJagged(a, b, c); }
更高效/另一种方式:
public static void ConvertFlatArrayToMatrix(int[] array, int[,] matrix, int dimension) { for(int i = 0; i < array.Length; i++) { int r = Mathf.FloorToInt(i / dimension); int c = i % dimension; matrix[c,r] = array[i]; } }
这只会将结果推送到您传入的2d数组中。
请记住,我不是在检查长度或防止任何事情,这只是完成工作的概念和最低限度。