-1

I have the following code, how can I get the values from the items in the listbox and get my program to find the average, highest and lowest of the values. I currently have the following textboxes (averageTextbox, highestTextbox, lowestTextbox) and I wish to display the values accordingly into the textboxes. Thanks in Advance!

private void readButton_Click(object sender, EventArgs e)
{
    int counter = 0;
    string line;
    System.IO.StreamReader file = new System.IO.StreamReader(
        @"C:\Users\Harra\Documents\Visual Studio 2017\Projects\File Reader\Sales.txt");
    double dblAdd = 0;

    while ((line = file.ReadLine()) != null)
    {
        displayListBox.Items.Add(line);
        dblAdd += Convert.ToDouble(line);
        counter++;
    }

    totalTextBox.Text = string.Format("{0:F}", dblAdd);
}
Rufus L
  • 36,127
  • 5
  • 30
  • 43
Relaxsingh
  • 11
  • 5

2 Answers2

1

Ed's answer is most likely the way to go, but here's another way you can do it (from any code that has access to your displayListBox).

Note that this only works after the ListBox has been populated with doubles. It also requires a reference to System.Linq, which provides extension methods that we make use of (Cast, Sum, Max, Min, and Average):

using System.Linq;

The following line will take all the ListBoxItems, cast them to strings, then convert them to doubles:

IEnumerable<double> listBoxDoubleItems = 
    displayListBox.Items.Cast<string>().Select(Convert.ToDouble);

Now that you have an IEnumerable<double> to work with, you can use the Linq extension methods to get what you're looking for:

double total = listBoxDoubleItems.Sum();
double highest = listBoxDoubleItems.Max();
double lowest = listBoxDoubleItems.Min();
double average = listBoxDoubleItems.Average();
Rufus L
  • 36,127
  • 5
  • 30
  • 43
0
double lowest = Double.MaxValue;
double highest = Double.MinValue;
double average = 0;

while ((line = file.ReadLine()) != null)
{
    displayListBox.Items.Add(line);

    var dbl = Convert.ToDouble(line);

    if (dbl > highest)
        highest = dbl;

    if (dbl < lowest)
        lowest = dbl;

    dblAdd += dbl;

    counter++;
}

if (counter > 0)
{
    average = dblAdd / (double)counter;
}
else
{
    highest = lowest = 0;
}

You already know how create a TextBox, and how to format a double and display it in a TextBox.