I would like to use a 2-D array but I can't know its size in advance. So my question is: how to declare it? And then how to add values into it?
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;
}
I know I can also use a list but I am not very familiar with it.
Thank you!
EDIT: Brace yourselves! Here come my true code with Jon Skeet's help!
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++;
}
}
And to call it:
foreach(string[] array in tabConfig)
foreach(String txt in array)
Console.WriteLine(txt);
So my question is: how to declare it?
You can't. All arrays in .NET are fixed size: you can't create an array instance without knowing the size.
It looks to me like you should have a List<T>
- and I'd actually create a class to hold the four properties, rather than just using four elements of an array, probably. You could use a list of arrays:
List<string[]> tabConfig = new List<string[]>();
foreach (...)
{
tabConfig.Add(new string[] { a, b, c, d });
}
... but then you need to know what those four elements mean in terms of ordering etc, which is likely to make the rest of your code harder to understand.
You can use a
List<List<string>>
for this, dont' you?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With