スキップしてメイン コンテンツに移動

投稿

ラベル(conversion)が付いた投稿を表示しています

C#: Convert 1 Dimensional Array to Fixed Size 2 Dimensional Array

Code using System; using System.Collections.Generic; using System.Linq; namespace Utility { public static class ArrayUtils { public static T[,] To2DimensionalArray (this T[] source, int block){ var ret = new T[block, source.Length/block]; for (int i = 0, offset = 0, len = ret.Length; offset < len; i++, offset = i * block) { for(int j = 0; j < block; j++){ ret[j, i] = source[offset + j]; } } return ret; } } } Example Usage int[] array1 = { 1, 2, 3, 4, 5, 6, 7, 8, 9}; int[,] array2 = array1.To2DimensionalArray(3); /* array2 will be... { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } } */

C#: Convert 1 Dimensional Array to 2 Dimensional Jagged Array

Code using System; using System.Collections.Generic; using System.Linq; namespace Utility { public static class ArrayUtils { public static T[][] To2DimensionalJaggedArray<T>(this T[] source, int block) { var res = new T[block][]; int size = source.Length / block; for (int i = 0; i < block; i++) { res[i] = new T[size]; Array.Copy(source, i*size, res, 0, size); // advantage of jagged array is that you can use Array.copy method etc. } return res; } } } Example Usage int[] array1 = { 1, 2, 3, 4, 5, 6, 7, 8, 9}; int[][] array2 = array1.To2DimensionalJaggedArray(3); /* array2 will be int[3][] and each elements will be... [0] = { 1, 2, 3 }, [1] = { 4, 5, 6 }, [2] = { 7, 8, 9 } */