0

I'm used to working with arrays in other languages, but I'm new to C# and I'm wondering how to just get the child array of a 2D array.

Here is what I've tried:

int[,] arr = new int[4, 4];
int[] childArr = arr[0];

My error is "Wrong number of indexes 1' inside [], expected 2'." The thing is, I want the child array, not something inside the child array which I think the error is telling me to do with the second index.

Thanks for the help.

Jack
  • 57
  • 7
  • Can you define what you mean by "child array"? Are you looking for something like [this](https://stackoverflow.com/a/1406218/2337077) – davidk Aug 14 '20 at 20:53
  • You _could_ implement your 2D array as a [jagged array](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/arrays/jagged-arrays) (`int[][] arr = new int[4][];`). Then you could access it in the way you want: `int[] childArr = arr[0]`. But be careful, as this structure doesn't enforce all "child" arrays to have the same length (which is where the term "jagged" comes from). .NET is optimized for 1D arrays, so depending on your usage, processing of jagged arrays may perform faster than 2D arrays. But 2D arrays are easier to read, initialize, and manage. – Sean Skelly Aug 14 '20 at 21:46

1 Answers1

1

2D arrays don't include a way to access a row or column. You're going to have to iterate. You can use extension methods to get an API similar to Math.NET's Matrix<T>

For example:

public static IEnumerable<T> Row<T>(this T[,] arr, int row)
{
    for (var i = 0; i < arr.GetLength(0); i++)
    {
        yield return arr[i, row];
    }
}

public static IEnumerable<T> Column<T>(this T[,] arr, int col)
{
    for (var i = 0; i < arr.GetLength(1); i++)
    {
        yield return arr[col, i];
    }
}

int[,] myArray;

...

int[] row0 = myArray.Row(0).ToArray();
int[] col0 = myArray.Column(0).ToArray();
Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70