I have a file with content:
4;10;3;6;10
6;9;1;3;5
3;2;1;1;2,65
I need to split each line of the file into an fractional (double) array with elements as these numbers. I was able to do this and the task works correctly. But the code looks cumbersome. Is there any way to optimize it?
string[] readText = File.ReadAllLines(@"*file_path_here*.txt");
string[] x = readText[0].Split(';');
string[] y = readText[1].Split(';');
string[] r = readText[2].Split(';');
double[] x1 = new double[x.Length];
double[] y1 = new double[y.Length];
double[] r1 = new double[r.Length];
for (int i= 0; i < x.Length; i++)
{
x1[i] = Convert.ToDouble(x[i]);
y1[i] = Convert.ToDouble(y[i]);
r1[i] = Convert.ToDouble(r[i]);
}
1 Answer 1
There's not really a way to optimize it if you're going to insist on calling the variables x
, y
, and z
, because you have to write into each of them. What you could do though is to have a List
of lists, which would look something like:
string[] readText = File.ReadAllLines(@"*file_path_here*.txt");
List<List<double>> yourData = new List<List<double>>();
foreach(var line in readText)
{
var columns = line.Split(';');
List<double> newData = new List<double>();
foreach(var column in columns)
{
newData.Add(Convert.ToDouble(column));
}
yourData.Add(newData);
}
This has the advantage that you can add as many rows as you want to the text file and they all get added automatically, and each row can have a different number of entries. You can still convert to arrays if you really need arrays, with Linq:
using System.Linq;
// Make yourData
double[] x = yourData[0].ToArray();
// Same for y, z
File.ReadAllLines(filePath).Select(x => x.Split(';').Select(Convert.ToDouble).ToArray()).ToArray();
\$\endgroup\$