2010-01-15 125 views
2

這裏試圖用循環初始化一個數組(c#)。行數將根據情況而變化。我需要回到計劃初期和週末早些時候計算的兩個值。很多使用循環構建int數組的示例,但沒有任何可以找到動態字符串和多個暗淡數組的示例。初始化多朦字符串數組

由於

我如何設置爲COL1的值在串[,] arrayWeeks =新的字符串[numWeeks中,col1];這更清楚嗎?

+1

你的問題是,到底是什麼? – 2010-01-15 14:34:13

+0

'2'標籤是什麼意思? – Amy 2010-01-15 14:46:19

回答

3

(謝謝你的澄清),你可以做一個多維初始化像這樣:

string[,] arrayWeeks = new string[,] { { "1", "2" }, { "3", "4" }, { "5", "6" }, { "7", "8" } }; 

或者,如果你的數組是鋸齒狀:

string[][] arrayWeeks = new string[][] 
{ 
    new string[] {"1","2","3"}, 
    new string[] {"4","5"}, 
    new string[] {"6","7"}, 
    new string[] {"8"} 
}; 

如果你在一個循環的時候,我猜你想要鋸齒。而不是使用值進行初始化,您可能需要調用arrayWeeks[x] = new string[y];,其中x是要添加的行,y是該行中元素的數量。然後您可以設置每個值:arrayWeeks[x][i] = ...您正在設置行中第i個元素的位置。你數組的初始宣佈將string[][] arrayWeeks = new string[numRows][];

因此,要總結,你可能想要的東西,看起來像這樣:

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"; 

但是,很明顯,你的循環中。

3

有兩種類型的你可能會在C#中調用「多維」數組。有真正的multidimensional arrays

string[,] array = new string[4, 4]; 
array[0, 0] = "Hello, world!"; 
// etc. 

也有jagged arrays。一個鋸齒形數組,其元素也是數組。鋸齒陣列中的「行」可以具有不同的長度。與交錯數組一個重要的注意的是,你必須手動初始化「行」:

string[][] array = new string[4][]; 
for(int i = 0; i < 4; i++) { 
    array[i] = new string[4]; 
} 
array[0][0] = "Hello, world!"; 
3

如果變化取決於一些因素(不固定),這將是更好地使用的容器,這樣的行數作爲清單(見list on the MSDN)。您可以在列表中嵌套列表以創建多維列表。

0

晚的談話,但這裏是一個交錯數組例如,當您設置的大小和數據動態:

// 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; 
    } 
}