文字列からC#のint[][]とchar[][]を作成する/int[][]から文字列を生成するクラス

C#のジャグ配列、、生成するのが面倒なのでちょっとしたヘルパー代わり。 でくくった文字列からint[]のジャグ配列を作成する。

  class GridCreator
  {
    /*
    入力サンプル
    [[3,0,8,4],[2,4,5,7],[9,2,6,3],[0,3,1,0]]
    ↓
    [3,0,8,4]
    [2,4,5,7]
    [9,2,6,3]
    [0,3,1,0]
    */
    public static int[][] CreateGridJag(string a)
    {
      string[] wk = a.Replace(" ", "").Replace("[[", "").Replace("]]", "").Split("],[");
      int[][] grid = new int[wk.Length][];
      for (int i = 0; i < wk.Length; i++)
      {
        string[] tmp = wk[i].Split(",");
                if (tmp.Length > 0 && tmp[0].Length > 0)
                    grid[i] = tmp.Select(x => int.Parse(x)).ToArray();
      }
      return grid;
    }
    public static int[,] CreateGrid(string a)
    {
      string[] wk = a.Replace(" ", "").Replace("[[", "").Replace("]]", "").Split("],[");
      int[][] tmp = wk.Select(c => c.Split(",").Select(x => int.Parse(x)).ToArray()).ToArray();
      int[,] grid = new int[tmp.Length, tmp[0].Length];

      for (int i = 0; i < wk.Length; i++)
      {
        for (int j = 0; j < tmp[i].Length; j++)
          grid[i, j] = tmp[i][j];
      }
      return grid;
    }
    public static char[][] CreateCharGrid(string a)
    {
      string[] wk = a.Replace(" ", "").Replace("[[", "").Replace("]]", "").Split("],[");
      char[][] grid = new char[wk.Length][];
      for (int i = 0; i < wk.Length; i++)
      {
        string[] tmp = wk[i].Split(",");
        grid[i] = tmp.Select(x => x[0]).ToArray();
      }
      return grid;
    }

    public static string GetResultStr(int[][] grid)
    {
      StringBuilder builder = new StringBuilder();
      builder.Append("[");
      foreach (var item in grid)
      {
        builder.Append("[");
        for (int i = 0; i < item.Length; i++)
        {
          if (i == item.Length - 1)
            builder.Append(item[i]);
          else
            builder.Append(item[i]).Append(",");
        }
        builder.Append("]");
      }
      builder.Append("]");
      return builder.ToString();
    }
  }

使い方

            int[][] grid = GridCreator.CreateGrid("[[3,0,8,4],[2,4,5,7],[9,2,6,3],[0,3,1,0]]");