Jedhi
Jedhi

Reputation: 73

Converting string array to double array

I have a file with alot of numbers, each index has 4 subnumbers

no1 no2 no3 no4 
no1 no2 no3 no4 
no1 no2 no3 no4 

The file is a cvs file, but I need to read the numbers into an array as type double and make an interpolating, so I need to walkthrough the table.

Until now I have this, but I am stuck and do not really know how I nicely can convert the file to double values, so I can start calculate on them. Any suggestion ?

var filelines = from line in file.Skip(5)
                select line.Split(';');

Upvotes: 0

Views: 334

Answers (3)

Transcendent
Transcendent

Reputation: 5755

If there is certain values in each row, like let's say your cvs data store has a specific number of fields, s wiser and strongly typed move is to first make up a model for your data store, which according to the information you provided would be:

public class MyCVSModel {
    public Double Number1 {get; set;} 
    public Double Number2 {get; set;} 
    public Double Number3 {get; set;} 
    public Double Number4 {get; set;} 
}

Now, you can:

public static IEnumerable<MyCVSModel> Converion(String FileName){
     var AllLines = System.IO.ReadAllLines(FileName);
     foreach(var i in AllLines){
        var Temp = i.Split('\t'); // Or any other delimiter
        if (Temp.Lenght >= 4){ // 4 is because you have 4 values in a row
           List<Double> TryConversion = new List<Double>();
           foreach(var x in Temp) {
              if (IsDouble(x))
                 TryConversion.Add(Convert.ToDouble(x));
              else
                 TryConversion.Add(0);
           }
           MyCVSModel Model = new MyCVSModel();
           Model.Number1 = TryConversion[0];
           Model.Number2 = TryConversion[1];
           Model.Number3 = TryConversion[2];
           Model.Number4 = TryConversion[3];
           yield return Model;
        }
     }
}

public static Boolean IsDouble(String Value) {
    Regex R = new Regex(@"^[0-9]*(?:\.[0-9]*)?$");
    return R.IsMatch(Value);
}

Upvotes: 0

Tim Schmelter
Tim Schmelter

Reputation: 460208

If you want a double[][], so one array per line:

double d;
double[][] lineValues = file.Skip(5)
    .Select(l => l.Split(new[]{';'}, StringSplitOptions.RemoveEmptyEntries))
    .Where(arr => arr.Length == 4 && arr.All(s => double.TryParse(s, out d)))
    .Select(arr => arr.Select(double.Parse).ToArray())
    .ToArray();

Upvotes: 1

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101701

You can split the line,parse each part into decimal and use SelectMany to flatten results:

file.Skip(5).SelectMany(line => line.Split(';').Select(decimal.Parse)).ToArray()

Upvotes: 1

Related Questions