-1

I'm trying to read a matrix from a txt, but it doesn't seem to work at all. How can you do it if you don't know the count of the rows and columns, so the matrix in the file can be different every time?

Thanks in advance!

moladori
  • 13
  • 3
  • Welcome! Can you give some more detail about what should be the destination of the read txt? Some code maybe – ntohl May 28 '20 at 09:12
  • Does this answer your question? [2d Array from text file c#](https://stackoverflow.com/questions/13724781/2d-array-from-text-file-c-sharp) – Drag and Drop May 28 '20 at 11:06
  • And here comes the related : https://stackoverflow.com/questions/38125249/splitting-text-file-into-2d-array , https://stackoverflow.com/questions/43096776/read-2d-matrix-from-file-to-2d-int-array-in-c-sharp, https://stackoverflow.com/questions/19595938/loading-data-into-a-2d-array-from-text-file, https://stackoverflow.com/questions/36210684/read-text-file-into-2d-double-array, https://stackoverflow.com/questions/1844276/c-sharp-text-file-to-2d-array , – Drag and Drop May 28 '20 at 11:08
  • https://stackoverflow.com/questions/1844276/c-sharp-text-file-to-2d-array , – Drag and Drop May 28 '20 at 11:09
  • sorry, I've edited it with a snippet – moladori May 29 '20 at 14:37

1 Answers1

1

You can try Linq in order to query file:

  using System.IO;
  using System.Linq;

  ...

  int[][] result = File
    .ReadLines(@"c:\myMatrix.txt")
    .Where(line => !string.IsNullOrWhiteSpace(line))
    .Select(line => line
       .Split(new char[] { '\t', ' ' }, StringSplitOptions.RemoveEmptyEntries)
       .Select(item => int.Parse(item))
       .ToArray())
    .ToArray();

Please, note, that often jagged array, i.e. array of array (int[][]) is more convenient than 2d one (int[,])

Edit: If you insist on 2D array you can get it from jagged one:

   int[,] result2D = new int[
     result.Length, 
     result.Any() ? result.Max(line => line.Length) : 0];

   for (int row = 0; row < result.Length; ++row) 
     for (int col = 0; col < result[row].Length; ++col)
       result2D[row, col] = result[row][col]; 
Dmitry Bychenko
  • 149,892
  • 16
  • 136
  • 186