arrays – How to create mutlidimensional list for this in C#? – Education Career Blog

I got a table (in file) which I split into blocks by spaces.

I need structure like this:


It’s more like each row is its own table. How should I do this?

I tried List<List<string>> matrix = new List<List<string>>(); but I can’t seem to find a way to work with it.

EDIT – can someone tell me what’s wrong with this code???? Matrix00 is same as matrix 10.. it seems that same row is added to matrix all the time, but I clear it …

static ArrayList ReadFromFile(string filename)
    StreamReader SR;
    string S;
    string S_split;

    SR = File.OpenText(filename);
    S = SR.ReadLine();

    ArrayList myItems = new ArrayList();

    List<List<string>> matrix = new List<List<string>>();
    List<string> row = new List<string>();

    while (S != null)
        S_split = S.Split(' ');
        for (int i = 1; i < S_split.GetLength(0); i++)

        S = SR.ReadLine();
    return myItems;


Not sure if I understand this correctly.

        List<List<int>> table = new List<List<int>>();
        List<int> row = new List<int>();
        row.Add(33); // and so on

        row = new List<int>();


The program should show a message box with text “33”.


You should be able to work with it as you’d expect to deal with a list within a list.

matrix.Add(new List<string>);
matrix0.Add("a string");


List<List<String>> matrix = new List<List<String>>();

foreach (String line in file)
   String values = line.Split(new Char { ' ' });

   matrix.Add(new List<String>(values));

Just iterate through your file and for every line do the following.

  1. Generate a new List
  2. Fill it with the data for the line
  3. Add the list for the current line to your list for the complete file

Note that foreach (String line in file) is just pseudo code. Further you can merge the to lines in the body to a single line.

matrix.Add(new List<String>(line.Split(new Char { ' ' })));


You’re describing a jagged array. I’m not exactly sure if a List won’t be overkill? If you just have to import the data from the file and than use it, a jagged array should be simple enough.


int jaggedArray = new int 
    new int {21, 22, 23, 33, 3323},
    new int {32, 32},
    new int {434433, 545454, 5454}

you can also buildup the jagged array in a loop while processing your file, like this:

int result = new intnumberOfLines;
for (int currentLine = 0; currentLine < numberOfLines; currentLine++)
    String line = fileStream.ReadLine();
    int values = SplitAndConvertLine(line);
    resultcurrentLine = values;


If you are trying to read from the file then try something like the following (Note the following code has not been run through a compiler)

List<string> matrix = new List<string>();
    var values = instream.ReadLine().Split(new {' '});

Leave a Comment