tags:

views:

242

answers:

3

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 LINQ? All I manged to do was creating a simple array with all first values in each row. Is using LINQ in this case a good idea or should I simply load the file normal way and parse it?

+2  A: 

Do you mean something like this?

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]);

Take a look to this web: LINK

Jonathan
you'd better split on a space since it's not comma delimited.
No Refunds No Returns
Oh.. Thanks. I Will Edit it.
Jonathan
There's no StreamReader.Lines() method... but it would be easy to create an extension method that enumerates all lines in the StreamReader
Thomas Levesque
+2  A: 
File.ReadAllLines(myFile)
    .Select(l => l.Split(' ')
        .Select(i => int.Parse(i)).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(i => int.Parse(i)).ToArray());
    }
}
var myArray = forThoseWhoHave1GigFiles.ToArray();
Yuriy Faktorovich
ReadAllLines loads all lines into memory... what if the file weighs 1GB ?
Thomas Levesque
Elegant! Except, you may want a second .ToArray() on the end to be able to assign it directly to a jagged array int[][].
Jesse C. Slicer
@Jesse: yes, both of my methods unfortunately assign it to a jagged array instead of [,].
Yuriy Faktorovich
+1  A: 

Just to complete Jonathan's answer, here's how you could implement the Lines extension method :

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