读取文本文件,拆分它,然后在列表框中显示
Read text file, split it, then show it in listBox
我需要读取包含时间戳和温度的文本文件。问题是,我只需要在列表框中显示温度,在显示之前拆分字符串。
到目前为止,我已经成功地在列表中显示了文本文件,但我正在努力删除时间戳。
我的代码:
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();
}
}
现在listBox只显示String[]数组。
哦,我还需要在我的代码中包含这个:
const int numOfTemp = 50;
double dailyTemp[numOfTemps];
文本文件格式如下:
11:11:11-10,50
你应该取 Split
之后数组的 [1]
项:
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();
}
}
我需要读取包含时间戳和温度的文本文件。问题是,我只需要在列表框中显示温度,在显示之前拆分字符串。 到目前为止,我已经成功地在列表中显示了文本文件,但我正在努力删除时间戳。
我的代码:
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();
}
}
现在listBox只显示String[]数组。 哦,我还需要在我的代码中包含这个:
const int numOfTemp = 50;
double dailyTemp[numOfTemps];
文本文件格式如下: 11:11:11-10,50
你应该取 Split
之后数组的 [1]
项:
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();
}
}