tags:

views:

34

answers:

4

my double data in text file like below:

1.4  2.3  3.4
2.2  2.5  2.5

I want simply read this data from file and store it in an array.

please help me. I'm a beginner in C#

+1  A: 

You can use LINQ:

double[] numbers = 
    File.ReadAllLines(path)
        .Select(s => double.Parse(s)
        .ToArray()

If each line can have multiple numbers, you'll need to split the lines:

double[] numbers = 
    File.ReadAllLines(path)
        .SelectMany(s => s.Split(' '))
        .Select(s => double.Parse(s)
        .ToArray()

You can also use a normal loop:

List<double> numbers = new List<double>();
foreach(string line in File.ReadAllLines(path)) {
    numbers.Add(Double.Parse(line));
}

Or, to split them,

List<double> numbers = new List<double>();
foreach(string line in File.ReadAllLines(path)) {
    foreach(string word in line.Split(' ') {
        numbers.Add(Double.Parse(word));
    }
}
SLaks
+1, although I think LINQ's a little too much for a beginner :)
BoltClock
@BoltClock - +1. Also let the beginners work with it a bit... posting code might 'give them a fish' so to speak..
Gishu
A: 

Try this, it should be somewhat more bulletproof than some of the other answers. It does not check for invalid data entries which can't be parsed correctly.

var doubles = File.ReadAllText(path)
              .Split(new[] {" ", "\r\n", "\n"}, StringSplitOptions.RemoveEmptyEntries)
              .Select(s => double.Parse(s, CultureInfo.GetCultureInfo("en-US"))).ToArray();

This will work if the doubles are splitted by either a space or a line break. And it also works if there are multiple spaces/line breaks. I live in DK so I have setted the culture info explicit for parsing.

lasseespeholt
A: 
var values = from value in File.ReadAllText("C:\\Yourfilename.txt").Split(' ')
             select double.Parse(value);
Botz3000
+1  A: 

Consult MSDN with the following pointers...

File class to read the file contents as string
String.Split to split the numbers based on your delimited
and Double.Parse to convert from string into double.

Gishu