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

投稿

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

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 } } */