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

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

コメント