How to find the lowest, highest and average values

2019-03-07 03:02发布

I'm trying to create a program that calculates and displays the highest, lowest and average value of items in a listbox (items generated from a txt file). I finally figured out how to load a text file to the listbox. I have been searching for clues for about an hour and all my attempts have brought me to a dead end.

my listbox is called readListbox and my Highest, Lowest and Average labels are called highestLabel, lowestLabel and averageLabel respectively. How do I go about creting this program. The numbers are in the decimal format. Any Help will be very much appreciated.

private void readButton_Click(object sender, EventArgs e)
{
    try
    {
        OpenFileDialog Open = new OpenFileDialog();
        if(Open.ShowDialog() == DialogResult.OK)
        {
            readListbox.Text = Open.FileName;
            string[] lines = System.IO.File.ReadAllLines(Open.FileName);
            readListbox.Items.AddRange(lines);
        }
    }
    catch
    {
        MessageBox.Show("Error");
    }

    }
}
}

1条回答
干净又极端
2楼-- · 2019-03-07 03:30

After reading the string elements of your file you need to convert them to decimal values. At that point you can use the built in methods of the IEnumerable extensions to get your data

OpenFileDialog Open = new OpenFileDialog();
if(Open.ShowDialog() == DialogResult.OK)
{
        readListbox.Text = Open.FileName;
        string[] lines = System.IO.File.ReadAllLines(Open.FileName);

        decimal[] values = lines.Select(x => decimal.Parse(x)).ToArray();
        labelHigh.Text = values.Max().ToString();
        labelMin.Text = values.Min().ToString();
        labelAvg.Text = values.Average().ToString();        

        readListbox.Items.AddRange(lines);
 }
查看更多
登录 后发表回答