• Advertisement
Sign in to follow this  

C# Reading double-precision numbers from file line at a time

This topic is 3000 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I'm hoping to run through a file, pulling in a line at a time. Each line will have n space delimited double-precision numbers in, like: 0.12345 2.345676 7.64686 5.687436 6.96846 0.235454 etc (n is known at runtime but not compile time) And I would prefer to grab a line, get the numbers into variables, process the variables, then rinse and repeat until the end of the file. So far I have:
FileStream file = new FileStream(path, FileMode.Open, FileAccess.Read);

            if (file.CanRead)
            {
                StreamReader sr = new StreamReader(file);

                while (!sr.EndOfStream)
                {
                    string buffer = sr.ReadLine();
                    List<double> valueList;
                    // now, buffer has double-precision numbers, space delimited
                    // which I want to end up in value[n]
                     
                    // ... other code...
                }
            }
But what I don't know is how best to get the numbers out of buffer and into my variables. I known of a String.Split method which takes a string and breaks it up into bits... is that the right direction to go?

Share this post


Link to post
Share on other sites
Advertisement
string[] values = buffer.Split(' ');

List<double> valueList = new List<double>();

foreach (string str in values)
{
valueList.Add(double.Parse(str));
}

Share this post


Link to post
Share on other sites
Here is one very compact implementation of what you want:

using System.Linq;
...
List<double> type = File.ReadAllLines("data.txt")
.Select(row => row.Split(' '))
.SelectMany(parts => parts, (parts, value) => double.Parse(value, CultureInfo.InvariantCulture))
.ToList();



- File.ReadAllLines reads all lines of text from a file (returns string[])
- Select(row => row.Split(' ')) invokes the Split method on each row and returns IEnumerable<string[]> in this case
- SelectMany(parts => parts, (parts, value) => double.Parse(value, CultureInfo.InvariantCulture)) flattens all those string arrays into a single enumeration of strings and than invokes double.Parse to convert each item into a a double, this returns an IEnumerable<double>
- finally, ToList transforms the IEnumerable<double> into a List<double>

I highly recommend to try to understand the code above. Being able to use this kind of functional paradigm is one of the most outstanding features of C# and helps a lot to write compact code.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement