我需要阅读一个包含时间戳和温度的文本文件。问题是,我只需要在列表框中显示温度,在显示字符串之前先将其拆分。到目前为止,我已经设法在列表中显示了文本文件,但是我在删除时间戳方面很挣扎。
我的代码:
public partial class Form1 : Form
{
OpenFileDialog openFile = new OpenFileDialog();
string line = "";
private void button1_Click(object sender, EventArgs e)
{
if (openFile.ShowDialog() == DialogResult.OK)
{
StreamReader sr = new StreamReader(openFile.FileName);
while(line != null)
{
line = sr.ReadLine();
if(line != null)
{
string[] newLine = line.Split(' ');
listBox1.Items.Add(newLine);
}
}
sr.Close();
}
}
现在列表框仅显示String []数组。哦,我也需要在代码中包含它:
const int numOfTemp = 50;
double dailyTemp[numOfTemps];
文本文件采用以下格式:11:11:11 -10,50
您应该在[1]
之后获取数组的Split
项:
using System.Linq;
...
private void button1_Click(object sender, EventArgs e)
{
if (openFile.ShowDialog() != DialogResult.OK)
return;
var temps = File
.ReadLines(openFile.FileName)
.Select(line => line.Split(' ')[1]); // we need temperature only
try {
listBox1.BeginUpdate();
// In case you want to clear previous items
// listBox1.Items.Clear();
foreach (string temp in temps)
listBox1.Items.Add(temp);
}
finally {
listBox1.EndUpdate();
}
}