【发布时间】:2013-12-11 14:08:40
【问题描述】:
我想使用二维数组,但我无法提前知道它的大小。所以我的问题是:如何声明它?那么如何给它加值呢?
String[,] tabConfig = new String[?, 4];
foreach(blabla with i)
{
tabConfig[i, 0] = a;
tabConfig[i, 1] = b;
tabConfig[i, 2] = c;
tabConfig[i, 3] = d;
}
我知道我也可以使用列表,但我不是很熟悉。
谢谢!
编辑:振作起来!在 Jon Skeet 的帮助下,我的真实代码出现了!
List<string[]> tabConfig = new List<string[]>();
String[] temp = new String[4];//The array that will be inside the List
int line = 0, column = 0;
foreach (XmlNode e in doc.DocumentElement.ChildNodes)
{
if (e.Attributes["Server"].Value == choice)
{
temp[0] = e.Attributes["Serveur"].Value;//Here is value 'a'
column = 1;
foreach (XmlNode i in e.ChildNodes)
{
temp[colonne] = i.InnerText;//Here are values 'b', 'c' and 'd'
column++;
}
tabConfig.Add(temp);//Put a new line into the List
line++;
}
}
并称它为:
foreach(string[] array in tabConfig)
foreach(String txt in array)
Console.WriteLine(txt);
【问题讨论】:
-
你不能计算你在循环中迭代的任何东西吗?
-
如果您需要动态调整大小,请改用列表列表(如果您知道一维,则使用列表列表的数组)。
List<List<string>>. -
所以你说我可以为(blabla i){ count++; } String[,] tabConfig = new String[count, 4];然后是我的 foreach(blabla i){} ?我不觉得它真的有利可图。我确信有一个更动态的解决方案。
-
我想用一个词来形容列表...它们是非常棒的东西...
标签: c# arrays multidimensional-array