Stuck here tryi开发者_运维问答ng to initialize an array (c#) using a loop. The number of rows will change depending. I need to get back two values that I am calculating earlier in the program startweek, and endweek. Lots of examples on building int arrays using loops but nothing I can find re dynamic strings and multi dim arrays.
Thanks
how do I set the values for col1 in string[,] arrayWeeks = new string[numWeeks, col1]; Is that clearer?
(Thanks for the clarification.) You can do a multidimensional initializer like so:
string[,] arrayWeeks = new string[,] { { "1", "2" }, { "3", "4" }, { "5", "6" }, { "7", "8" } };
Or, if your array is jagged:
string[][] arrayWeeks = new string[][]
{
new string[] {"1","2","3"},
new string[] {"4","5"},
new string[] {"6","7"},
new string[] {"8"}
};
If you're in a loop, I'm guessing you want jagged. And instead of initializing with values, you may want to call arrayWeeks[x] = new string[y];
where x is the row you're adding and y is the number of elements in that row. Then you can set each value: arrayWeeks[x][i] = ...
where you are setting the ith element in the row. Your initial declaration of the array would be string[][] arrayWeeks = new string[numRows][];
So, to summarize, you probably want something that looks like this:
int numRows = 2;
string[][] arrayWeeks = new string[numRows][];
arrayWeeks[0] = new string[2];
arrayWeeks[0][0] = "hi";
arrayWeeks[0][1] = "bye";
arrayWeeks[1] = new string[1];
arrayWeeks[1][0] = "aloha";
But, obviously, within your loop.
There are two types of what you might call "multidimensional" arrays in C#. There are genuine multidimensional arrays:
string[,] array = new string[4, 4];
array[0, 0] = "Hello, world!";
// etc.
There are also jagged arrays. A jagged array an array whose elements are also arrays. The "rows" in a jagged array can be of different lengths. An important note with jagged arrays is that you have to manually initialize the "rows":
string[][] array = new string[4][];
for(int i = 0; i < 4; i++) {
array[i] = new string[4];
}
array[0][0] = "Hello, world!";
If the number of rows change depending on some factor (not fixed), it would be better to use a container, such as a List (see list on the MSDN). You can nest a list within a list to create a multi-dimensional list.
Late to the conversation, but here is a jagged array example when you setting the size and data dynamically:
// rowCount from runtime data
stringArray = new string[rowCount][];
for (int index = 0; index < rowCount; index++)
{
// columnCount from runtime data
stringArray[index] = new string[columnCount];
for (int index2 = 0; index2 < columnCount; index2++)
{
// value from runtime data
stringArray[index][index2] = value;
}
}
精彩评论