Reading text data from a file using LINQ

I have the following text file:

37 44 60
67 15 94
45 02 44

How to read all numbers from this file and save them to a two-dimensional array using LINQ? All I managed to do was create a simple array with all the first values ​​in each row. Is using LINQ in this case a good idea or should I just upload the file in the usual way and parse it?

+3
source share
3 answers
File.ReadAllLines(myFile)
    .Select(l => l.Split(' ').Select(int.Parse).ToArray()).ToArray();

Or:

List<int[]> forThoseWhoHave1GigFiles = new List<int[]>();
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 higher.

+10
source

Just to answer Jonathan, here is how you could implement the extension method Lines:

public static class TextReaderExtensions
{
    public static IEnumerable<string> Lines(this TextReader reader)
    {
        string line;
        while((line = reader.ReadLine()) != null) yield return line;
    }
}
+4
source

- ?

StreamReader sr = new StreamReader("./files/someFile.txt");

      var t1 =
        from line in sr.Lines()
        let items = line.Split(' ')
        where ! line.StartsWith("#")
        select String.Format("{0}{1}{2}",
            items[1],
            items[2],
            items[3]);

-: LINK

+2

Source: https://habr.com/ru/post/1733379/


All Articles