我的代码允许用户选择要读取的txt文件并将行数传递给绘图函数:
private void Load_data_Click(object sender, EventArgs e)
{
Stream myStream = null;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = "C:\\DataArray";
openFileDialog1.Filter = "txt files (*.txt)|*.txt";
openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
if ((myStream = openFileDialog1.OpenFile()) != null)
{
using (myStream)
{
string filename = openFileDialog1.FileName;
var lineCount = 0;
using (var reader = File.OpenText(@filename))
{
while (reader.ReadLine() != null)
{
lineCount++;
}
}
var lines = lineCount;
ShowGraphData(lines);
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
}
然后该函数接收行数为lTotalData:
public void ShowGraphData(long lTotalData)
{
double[] dx = new double[lTotalData];
double[] dy = new double[lTotalData];
for (long li = 0; li < lTotalData; li++)
{
dx[li] = GlobalDataClass.dDataArray[li, 0];
dy[li] = GlobalDataClass.dDataArray[li, 1];
}
我的文字数据如下:
1,0
1,1
2,1
2,2
我的问题是如何做到:
for循环将循环行并检索数据ex:
dx [0,0] = 1
dy [0,1] = 0等等......
并将其保存在dx,dy数组中:
答案 0 :(得分:1)
我会使用数组数组而不是两个数组(dx
,dy
)
double[][] d = File.ReadLines(filename)
.Select(x => Array.ConvertAll(x.Split(','), n => double.Parse(n)))
.ToArray();
Console.WriteLine(d[0][1]);
答案 1 :(得分:0)
试试这个:
var numbers = File.ReadLines("path")
.SelectMany(x => x.Split(','))
.Select(x => Convert.ToDouble(x))
.ToList();
double[] dx = new double[numbers.Count];
double[] dy = new double[numbers.Count];
for (long li = 0; li < numbers.Count; li+=2)
{
dx[li] = numbers[li];
dy[li] = numbers[li +1];
}