C# 文件到一个数组,然后到文件中的所有数字

C# 文件到一个数组,然后到文件中的所有数字,c#,C#,我正在试图合计文件中的数字。我是个新手,不知道该怎么做。这就是我目前所拥有的。这需要我进一步解释,但我不确定还能写些什么。我所知道的是我有一个文件,我把它输出到一个数组中。文件中的数字需要在文本框中相加。解决了…我添加了一个for循环,解决了问题 这是代码 private void totalButton_Click(object sender, EventArgs e) { try { const int SIZE = 7

我正在试图合计文件中的数字。我是个新手,不知道该怎么做。这就是我目前所拥有的。这需要我进一步解释,但我不确定还能写些什么。我所知道的是我有一个文件,我把它输出到一个数组中。文件中的数字需要在文本框中相加。解决了…我添加了一个for循环,解决了问题

这是代码

    private void totalButton_Click(object sender, EventArgs e)
    {
        try
        {
            const int SIZE = 7;
            double[] numbers = new double [SIZE];
            double total = 0;
            int index = 0;

            StreamReader inputFile;

            inputFile = File.OpenText("Sales.txt");


                while (index < numbers.Length && !inputFile.EndOfStream)
                {
                    numbers[index] = double.Parse(inputFile.ReadLine());
                    index++;
                }
                for (index = 0; index < numbers.Length; index++)
                {
                    total += numbers[index];
                    totalTextBox.Text = total.ToString();
                }
            inputFile.Close();

            foreach (double value in numbers)
            {
                listBox1.Items.Add(value);

            }

    }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
}

    private void exitButton_Click(object sender, EventArgs e)
    {
        this.Close();
    }

}
private void totalButton\u单击(对象发送者,事件参数e)
{
尝试
{
常数int SIZE=7;
双精度[]数字=新的双精度[尺寸];
双倍合计=0;
int指数=0;
StreamReader输入文件;
inputFile=File.OpenText(“Sales.txt”);
while(索引

}

语句中,只需添加
总数+=数字[索引]
,然后在末尾,
myLabel.Text=total.ToString()


index
将为您提供值的计数。

while
语句中,只需添加
total+=numbers[index]
,然后在末尾,
myLabel.Text=total.ToString()


index
将为您提供值的计数。

使用
System.Linq
(和
File.ReadAllLines(String)
更简单的方法,因此您不必使用
while(){}
循环):

参考资料:


使用
System.Linq
(和
File.ReadAllLines(String)
更简单的方法,因此您不必使用
while(){}
循环):

参考资料:


你的意思是你想要数组中所有数字的总和吗?你已经有了进入数组的数字,对吗?只需在while语句中记录它们。编辑-Francois说的。我做了Francois说的,但我得到了一个运行时错误。它表示索引超出了数组的边界。我的新代码在上面。你的意思是你想要数组中所有数字的总和吗?你已经有了进入数组的数字,对吗?只需在while语句中记录它们。编辑-Francois说的。我做了Francois说的,但我得到了一个运行时错误。它表示索引超出了数组的边界。上面是我的新代码,它说索引超出了添加for循环所需的数组的界限。for(index=0;index// read the file in (broken apart by lines) in to an array: String[] lines = File.ReadAllLines("Sales.txt"); // Try parsing them to Double values: Double[] numbers = lines.Select(line => { Double val = 0; Double.TryParse(line, out val); return val; }); // Sum then using .Sum Double total = lines.Sum();