Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring a 2D array without knowing its size in C#

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);
like image 421
Sphax Avatar asked Nov 29 '22 15:11

Sphax


2 Answers

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.

like image 181
Jon Skeet Avatar answered Dec 05 '22 18:12

Jon Skeet


You can use a

List<List<string>> 

for this, dont' you?

like image 41
Oscar Avatar answered Dec 05 '22 16:12

Oscar