How can I convert a text file into a list of int arrays

后端 未结 5 2041
温柔的废话
温柔的废话 2021-01-16 19:02

I have a text file containing the following content:

0 0 1 0 3 
0 0 1 1 3 
0 0 1 2 3 
0 0 3 0 1 
0 0 0 1 2 1 1 
0 0 1 0 3 
0 0 1 1 3 
0 0 1 2 3 
0 0 3 0 1 
0         


        
5条回答
  •  自闭症患者
    2021-01-16 19:35

    using System.IO;
    using System.Linq;
    
    string filePath = @"D:\Path\To\The\File.txt";
    List listOfArrays =
        File.ReadLines(path)
        .Select(line => line.Split(' ').Select(s => int.Parse(s)).ToArray())
        .ToList();
    

    Since you mention that it is your first time programming in C#, this version may be easier to understand; the process is the same as the above:

    using System.IO;
    using System.Linq;
    
    string filePath = @"D:\Path\To\The\File.txt";
    
    IEnumerable linesFromFile = File.ReadLines(path);
    
    Func convertStringToIntArray =
        line => {
            var stringArray = line.Split(' ');
            var intSequence = stringArray.Select(s => int.Parse(s)); // or ....Select(Convert.ToInt32);
            var intArray = intSequance.ToArray();
            return intArray;
        };
    
    IEnumerable sequenceOfIntArrays = linesFromFile.Select(convertStringToIntArray);
    
    List listOfInfArrays = sequenceOfIntArrays.ToList();
    

提交回复
热议问题