Robin
Robin

Reputation:

C# - Multidimensional int arrays

How do you declare a "deep" array in C#?

I would like to have a int array like: [ 1, 4, 5, 6, [3, 5, 6, 7, 9], 1, 4, 234, 2, 1,2,4,6,67, [1,2,4,44,56,7] ]

I've done this before, but can't remember the right syntax. But it was something a like what is written below: Int32[] MyDeepArray = new Int32[] = {3, 2, 1, 5, {1, 3, 4, 5}, 1, 4, 5};

And how do I iterate it correctly.. How do I check that an array is an array?

Thanks!

Upvotes: 4

Views: 1384

Answers (5)

T Newc
T Newc

Reputation: 9

Another way to have an array of arrays.

int[,] myArray = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
    
for(int i=0; i < 3; i++)
{
    for(int x=0; x < 3; x++)
    {
        Console.WriteLine(myArray[i,x]);
    }
}

Upvotes: 0

David Hedlund
David Hedlund

Reputation: 129832

As for "how do I check that an array is an array": C# is strongly typed. anything that is declared as an array must be an array. what you are looking for is an array, not of integers, but of arrays of integers. therefore, every item in your outer array is a strongly typed array of integers. it's not integers and arrays of integers all mixed up. the closest thing you'll get is int-arrays and int-arrays-containing-only-one-int all mixed up. given that, you can always iterate through them, regardless, because they are all arrays, you can treat them all like arrays, and those that only contain one item will only step into the iteration once.

if you want to explicitly check, because you're treating the int-arrays-with-only-one-int differently, then you can check for their .Length value.

Upvotes: 0

CodeFusionMobile
CodeFusionMobile

Reputation: 15130

Here's some good documentation on using C# arrays. There's some information about iteration using foreach and other methods too.

http://msdn.microsoft.com/en-us/library/aa288453(VS.71).aspx

Upvotes: 1

JasCav
JasCav

Reputation: 34652

Int32[][] will allow you to declare a 2-dimensional array where the dimensions do not all have to be the same. So, for example, you could have the following:

[
[2,3,4,5]
[5]
[1,2,3,4,5,6,7,8]
[3,5]
[4]
]

The alternative is Int32[,] where the dimensions always have to be the same.

I'm not sure what you mean by "how do I check that an array is an array."

Upvotes: 1

Joseph
Joseph

Reputation: 25523

I believe the term you're looking for is a jagged array.

It can be done like this:

int[][] jaggedArray2 = new int[][] 
{
    new int[] {1,3,5,7,9},
    new int[] {0,2,4,6},
    new int[] {11,22}
};

And you can iterate through them like this:

for(int i = 0; i < jaggedArray2.Length; i++)
    for(int j = 0; j < jaggedArray2[i].Length; j++)
    {
        //do something here.
    }

Upvotes: 7

Related Questions