0
\$\begingroup\$

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]);
}
asked Oct 11, 2022 at 17:10
\$\endgroup\$
2
  • 4
    \$\begingroup\$ Have you learned about defining your own functions? \$\endgroup\$ Commented Oct 11, 2022 at 18:03
  • \$\begingroup\$ you could use linq like this File.ReadAllLines(filePath).Select(x => x.Split(';').Select(Convert.ToDouble).ToArray()).ToArray(); \$\endgroup\$ Commented Oct 14, 2022 at 14:39

1 Answer 1

1
\$\begingroup\$

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
answered Oct 12, 2022 at 18:22
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.