2016-11-26 44 views
1

我想出了如何使用StreamReader来读取文本文件。现在我必须创建一个数组,并在价格index[1]中合计所有的值。创建从使用StreamReader获得的数组和总值

我的数据如下:

黄色出租车,62.12,16年10月17日

福来鸡,9.50,16年10月18日

我目前只有10条线路,但是,未来可能会有更多的线路被添加。

我想在txtBox_Total.text = Total.ToString();

这里添加62.12和9.50,并进入总被我当前的代码:

private void btn_CalculateLoadExpenses_Click(object sender, EventArgs e) 
{ 
    string currentLine; 
    // Create StreamReader object to read Exams.txt 
    StreamReader examsReader = new StreamReader("TravelExpenses.txt"); 

    listBox_Output.Items.Clear(); 

    while (examsReader.EndOfStream == false) 
    { 
     currentLine = examsReader.ReadLine(); 
     listBox_Output.Items.Add(currentLine); 
    } 
} 
+0

'File.ReadAllLines'是一个容易得多如Damith的答案提示。如果你真的想在某种情况下使用'StreamReader',你应该在使用它之后关闭**阅读器,或者在'using'语句中包装流。 'File.ReadAllLines'会自动为你做这个。 – Jim

+0

@Jim:在此期间更容易但更慢。 StreamReader更好。 – Transcendent

+1

@Transcendent是的,这是正确的,我的评论并不意味着'File.ReadAllLines'更快。但事实上,值得一提的是赞成和反对者是什么。谢谢。 ...我不得不提这也取决于文件的大小。如果该文件仅包含例如20行......差异将会是* 0.007 ms *或多或少。 – Jim

回答

1

您可以阅读以外的所有线路使用File.ReadAllLines

string[] lines = File.ReadAllLines("TravelExpenses.txt"); 

然后添加全部使用Items.AddRange

listBox_Output.Items.AddRange(lines); 

和一个从字符串通过拆分采取和采取数之和像下面

var Total= lines.Select(line =>line.Split(',')[1]).Select(num =>decimal.Parse(num)).Sum(); 
txtBox_Total.text = Total.ToString(); 
+0

'ReadAllLines'很慢。在StreamReader中使用'ReadLine'方法是一种读取文件的更快的方法。而你的方式也使整个事情变得更慢。 – Transcendent

+1

是的,的确如此。但它取决于文件大小,您不会注意到小文件的性能增益。 (在列表框上显示100万条记录是不实际的) – Damith

+0

嗯,我经常在数据挖掘项目上工作,在我需要加载大型纯文本文件的地方。我注意到'ReadAllLines'可以简单地延迟包含10,000行或更多行的文本文件。这种纯文本文件的大小并不少见(在现实世界的情况下),这就是为什么我对你的文章发表评论,否则对于小文件你的方法就没有问题。 – Transcendent

0

我必须使用的StreamReader这个任务。这是我写的更多代码。有些东西仍然不正确,因为我的总计不工作。恐怕我会让它变得比需要的更复杂。

私人无效btn_CalculateLoadExpenses_Click(对象发件人,EventArgs的) {

 string[] purchase = new string[10]; 
     float[] price = new float[10]; 

     int index = 0; 

     string currentLine; 
     string[] fields; 
     float purchaseTotal, total = 0; 
     // Create StreamReader object to read Exams.txt 
     StreamReader examsReader = new StreamReader("TravelExpenses.txt"); 

     listBox_Output.Items.Clear(); 

     while (examsReader.EndOfStream == false) 
     { 
      currentLine = examsReader.ReadLine(); 
      fields = currentLine.Split(','); 
      listBox_Output.Items.Add(currentLine); 

      purchase[index] = fields[0]; 
      price[index] = total; 

      index++; 
      purchaseTotal = total; 

      txt_Box_Total.Text = total.ToString(); 
     } 

     examsReader.Close(); 
    }