Fast and efficient way to read a space separated file of numbers into an array?

后端 未结 7 737
情话喂你
情话喂你 2021-01-21 03:42

I need a fast and efficient method to read a space separated file with numbers into an array. The files are formatted this way:

4 6
1 2 3 4 5 6
2 5 4 3 21111 101         


        
7条回答
  •  梦谈多话
    2021-01-21 04:21

    Lets assume we've read the entire file into a string.
    You say the first two are rows and columns, so what we definitely need is to parse the numbers.
    After that, we can take the first two, create our data structure, and fill it accordingly.

    var fileData = File.ReadAllText(...).Split(' ');
    var convertedToNumbers = fileData.Select(entry => int.Parse(entry));
    int rows = convertedToNumbers.First();
    int columns = convertedToNumbers.Skip(1).First();
    // Now we have the number of rows, number of columns, and the data.
    int[,] resultData = new int[rows, columns];
    // Skipping over rows and columns values.
    var indexableData = convertedToNumbers.Skip(2).ToList();
    for(int i=0; i

    An alternative would be to read the first two from a stream, initialize the array, and then read n values at a time, which would be complicated. Also, it's best to keep files open for the shortest time possible.

提交回复
热议问题