1

I need to assign values to 2D array but I can't find the right syntax. I tried this but is't wrong:

string[][] s2d = new string[][] {
  {"val1","val2"},
  {"val1bis","val2bis"}
};

Thanks

4 Answers 4

8

You are almost there, just change the convention and use [,]., [][] used to define Array of arrays (Jagged arrays).

string[,] s2d = new string[,] {
  {"val1","val2"},
  {"val1bis","val2bis"}
};

If you want to enumerate on Multidimensional arrays you can do that but it is a flatten array.

foreach(var s in s2d) 
{
    // logic
}

Just access the elements in traditional way (if want).

for(int i=0;i < s2d.GetLength(0);i++)
    for(int j=0;j < s2d .GetLength(1);j++)
        var val = s2d [i,j];
Sign up to request clarification or add additional context in comments.

1 Comment

My problem is the next foreach. See comment below. Thanks
2

You're using an incorrect syntax:

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

Source: https://msdn.microsoft.com/it-it/library/2yd9wwz4.aspx

1 Comment

I need to use in a foreach: foreach (string[] s in sd2){}. With string[,] is not working.
1

If you truly want a 2d array

string[,] s2d = new string[2,2] { {"val1","val2"}, {"val1bis","val2bis"}};

string[][] gives you a possibility of a jagged array

5 Comments

I need to use in a foreach: foreach (string[] s in sd2){}. With string[,] is not working.
so you didnt want a array of 2d, you wanted a jagged array of any number of arrays.. thats a big difference
Yes, sort of. What I need, at the end, is a fast way to define a set of values on which do some operations: I need to create a bunch of nodes in an XML, and I use s[0]=nodeName and s[1]=value. The array-of-array is the fastest way i got to write code without replication.
Well this way you would use foreach ( string[2] s in sd2) which would give you s[0] and s[1]
it doesn't work. I've found this with the same solution using string[][]
0

If you really want array of arrays so declare array of arrays

string[][] s2d = new string[][] {
  new string[] {"val1","val2"},
  new string[] {"val1bis","val2bis"}
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.