如何从列表框中获取平均值、最高值和最低值,然后将其显示在文本框中

How do i get the Average, Highest and Lowest of values from a listbox and then display it on a textbox

我有以下代码,如何从列表框中的项目中获取值并让我的程序找到平均值、最高值和最低值。我目前有以下文本框(averageTextbox、highestTextbox、lowestTextbox),我希望相应地在文本框中显示这些值。提前致谢!

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);
}
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;
}

您已经知道如何创建文本框,以及如何格式化 double 并将其显示在文本框中。

Ed 的回答很可能是可行的方法,但还有另一种方法可以做到(从任何可以访问您的 displayListBox 的代码)。

请注意,这仅在 ListBoxdoubles 填充后有效。它还需要引用 System.Linq,它提供了我们使用的扩展方法(CastSumMaxMinAverage):

using System.Linq;

以下行将获取所有 ListBoxItems,将它们转换为 strings,然后将它们转换为 doubles

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

既然您有一个 IEnumerable<double> 可以使用,您可以使用 Linq 扩展方法来获得您要查找的内容:

double total = listBoxDoubleItems.Sum();
double highest = listBoxDoubleItems.Max();
double lowest = listBoxDoubleItems.Min();
double average = listBoxDoubleItems.Average();