How to initialize multi-dimensional array with different default value

后端 未结 2 1926
暗喜
暗喜 2021-01-17 17:18

I am trying to initialize 2-dimensional array of integer values with -1. When I create a new array, it is automatically filled with 0. I know I can do it with 2 for cycles,

相关标签:
2条回答
  • 2021-01-17 17:36

    Try something like this: int[,] array2D = new int[,] { { -1 }, { -1 }, { -1 }, { -1} };

    or with dimension int[,] array2D = new int[4,2] { { -1,-1 }, { -1,-1 }, { -1,-1 }, {-1,-1} };

    0 讨论(0)
  • 2021-01-17 17:43

    With a multidimensional array, the loops are most likely the best approach, unless the array is small enough to initialize directly in code.

    If you're using a jagged array, you could initialize the first sub-array, then use Array.Copy to copy these values into each other sub-array. This will still require one iteration through the first sub array, and one loop through N-1 outer arrays, but the copy operation will be faster than the loops.

    0 讨论(0)
提交回复
热议问题