简体   繁体   中英

How can I read a 2d array/matrix from file in C#, which is seperated with tab keys

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!

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, ie 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]; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM