-2

Let's imagine I have a 2d array (which basically is array of arrays). I want to have a reference to internal arrays to sort them directly or use them as arguments to some function.

type[,] array = new type[n,n] I cannot refer to inner array with array[index] because compiler expects me to input 2 indexes.

Yan Ulya
  • 21
  • 4
  • Suggested reading: **[Multidimensional Arrays (C# Programming Guide)](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/arrays/multidimensional-arrays)** – Ňɏssa Pøngjǣrdenlarp Mar 03 '23 at 00:46
  • 6
    I think what you want is a [Jagged Array (C# Programming Guide)](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/arrays/jagged-arrays) instead of a Multidimensional Array. – Thomas Mar 03 '23 at 00:49

2 Answers2

0

What you will want to use is a jagged array (arrays within an array):

A jagged array is an array whose elements are arrays, possibly of different sizes. A jagged array is sometimes called an "array of arrays." The following examples show how to declare, initialize, and access jagged arrays.

The following is a declaration of a single-dimensional array that has three elements, each of which is a single-dimensional array of integers:

int[][] jaggedArray = new int[3][];

Read more here:

https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/arrays/jagged-arrays

Pete
  • 106
  • 7
0

Two dimensional arrays are similar to an array of arrays, but probably the easiest way to think about them is as a grid of rows and columns. In fact, probably the most common usage is to represent a grid where the first index represents the row, and the second index represents the column of the value you're looking for, and you access items like: var item = array[row, col];

It sounds like you want to get a specific row from a two-dimensional array. One way to do this is to get the length of the second dimension (the number of columns) and then iterate through the array at a specific row value to get all the items from that row:

//                           row 0     row 1     row 2     row 3
var array2D = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };

var rowIndex = 0;
var numCols = array2D.GetLength(1);
var row0Items = new List<int>();
        
for (int i = 0; i < array2D.GetLength(1); i++) row0Items.Add(array2D[rowIndex, i]);

If you want to instead convert a two-dimensional array into a jagged array (which is made to be treated as an array of arrays), you could do something like:

int[,] array2D = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };

int[][] jagged = new int[array2D.GetLength(0)][];

for (int row = 0; row < array2D.GetLength(0); row++)
{
    var currentRow = new List<int>();

    for (int col = 0; col < array2D.GetLength(1); col++)
    {
        currentRow.Add(array2D[row, col]);
    }

    jagged[row] = currentRow.ToArray();
}
Rufus L
  • 36,127
  • 5
  • 30
  • 43