如何在列表框中找到最低、最高和平均值

How to find the lowest, highest and average values in a listbox(如何在列表框中找到最低、最高和平均值)
本文介绍了如何在列表框中找到最低、最高和平均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个程序来计算和显示列表框中项目的最高、最低和平均值(从 txt 文件生成的项目).我终于想出了如何将文本文件加载到列表框.我一直在寻找线索大约一个小时,我所有的尝试都把我带到了死胡同.

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.

我的列表框称为 readListbox,我的最高、最低和平均标签分别称为最高标签、最低标签和平均标签.我该如何着手创建这个程序.数字采用十进制格式.任何帮助将不胜感激.

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

    }
}
}

推荐答案

读取文件的字符串元素后,您需要将它们转换为十进制值.此时,您可以使用 IEnumerable 扩展的内置方法来获取数据

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

这篇关于如何在列表框中找到最低、最高和平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)