Let's say initialized a two-dimensional array

string[,] arr = { {"1", "2", "3"}, {"4", "5", "6"}, {"7", "8", "9"}, {"10", "11", "12"} }; 

Is it possible to somehow access the array string as a one-dimensional array?

    3 answers 3

    No, you can't do that.

    But you can write a wrapper that will "look" like a one-dimensional array. For example:

     public struct ArrayRow<T> { private readonly T[,] array; private readonly int row; public ArrayRow(T[,] array, int row) { this.array = array; this.row = row; } public int Length { get { return array.GetLength(1); } } public T this[int column] { get { return array[row, column]; } set { array[row, column] = value; } } } 

    But a similar structure, although it looks like an array, cannot be transferred instead of an array.

    However, if you add code, you can make this structure implement the IList<T> interface, which the arrays implement too - this will allow you to use the same code for working with regular arrays and with similar cuts.

      Multidimensional arrays are stored in memory as one continuous one-dimensional array. When accessing by the index [i, j] , a specific position in this internal one-dimensional array is calculated and the value is returned.

      Since there is no internal representation in the form of separate arrays, it is impossible to turn to them. The only way to get a one-dimensional array is to create it manually and copy the values ​​there, but it will be a copy of the array, with individual elements.

      • And through the links perhaps something? - e1s
      • There is a suspicion that you can somehow dodge, although yes, there is no normal way. - Qwertiy
      • 2
        For links in Sharp can and beat = D. But seriously - can you initially present the data as a one-dimensional array? Even values ​​- measurement 1 and odd - measurement 2. One-dimensional arrays are processed faster, so this method is common for example for representing arrays of coordinates and geodata (X, Y). - Anatoly Nikolaev
      • @ e1s is the only way links can help is if the array elements themselves are reference types, And you use / change their contents (i.e., do not use a[x] = myObj , but a[x] = myObj through properties / methods, for example a[x].myProp = 18 ); but in this case, you still need to first create a separate copy of a piece of a multidimensional array - Lanorkin

      And this option is not good?

       string[][] arr = new string[][] { new string[] {"1", "2", "3"}, new string[] {"4", "5", "6"}, new string[] {"7", "8", "9"}, new string[] {"10", "11", "12"} }; 
      • Thank you for the option, I considered this, in fact, it is a "ragged array" or an array of arrays, and we are talking about a two-dimensional - e1s
      • @ e1s, yes. But you just want to address the string as a one-dimensional address - in this case, torn instead of two-dimensional seems more appropriate. - Qwertiy