Read text data from file using LINQ

前端 未结 3 740
小蘑菇
小蘑菇 2021-02-03 16:24

I have following text file:

37 44 60
67 15 94
45 02 44

How to read all numbers from this file and save them into two-dimensional array, using L

3条回答
  •  终归单人心
    2021-02-03 16:48

    File.ReadAllLines(myFile)
        .Select(l => l.Split(' ').Select(int.Parse).ToArray()).ToArray();
    

    Or:

    List forThoseWhoHave1GigFiles = new List();
    using(StreamReader reader = File.OpenText(myFile))
    {
        while(!reader.EndOfStream)
        {
            string line = reader.ReadLine();
            forThoseWhoHave1GigFiles.Add(line.Split(' ')
                .Select(int.Parse).ToArray());
        }
    }
    var myArray = forThoseWhoHave1GigFiles.ToArray();
    

    And:

    File.ReadLines(myFile)
        .Select(l => l.Split(' ')
        .Select(int.Parse).ToArray())
        .ToArray();
    

    In .Net 4.0 and above.

提交回复
热议问题