【问题标题】:Read text file, split it, then show it in listBox读取文本文件,将其拆分,然后在 listBox 中显示
【发布时间】:2020-03-16 14:45:06
【问题描述】:

我需要阅读一个包含时间戳和温度的文本文件。问题是,我只需要在列表框中显示温度,在显示之前拆分字符串。 到目前为止,我已经设法在列表中显示文本文件,但我在努力删除时间戳。

我的代码:

     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

【问题讨论】:

    标签: c# winforms listbox openfiledialog


    【解决方案1】:

    你应该在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();
            } 
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-23
      • 2014-08-07
      • 1970-01-01
      • 2021-07-21
      • 1970-01-01
      • 2013-05-31
      相关资源
      最近更新 更多