Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ionic-framework/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 添加从列表框中选择的所有值_C#_Listbox_Double_Average - Fatal编程技术网

C# 添加从列表框中选择的所有值

C# 添加从列表框中选择的所有值,c#,listbox,double,average,C#,Listbox,Double,Average,这就是我已经走了多远,我不是很确定。 因此,我用诸如1.2、1.3之类的值填充了我的listbox1 那么,如何添加列表框的所有选定值并计算平均值呢? 如果你能帮助我,我将非常感激 List<double> doubleList = new List<double>(); private void btnGetAverage_Click(object sender, EventArgs e) { if (listBox1.Selec

这就是我已经走了多远,我不是很确定。 因此,我用诸如1.2、1.3之类的值填充了我的listbox1 那么,如何添加列表框的所有选定值并计算平均值呢? 如果你能帮助我,我将非常感激

    List<double> doubleList = new List<double>();
    private void btnGetAverage_Click(object sender, EventArgs e)
    {
        if (listBox1.SelectedIndex != -1)
        {
        }
    }
List doubleList=新列表();
私有无效btnGetAverage\u单击(对象发送者,事件参数e)
{
如果(listBox1.SelectedIndex!=-1)
{
}
}

您可以使用平均法:

List<double> doubleList = new List<double>();
private void btnGetAverage_Click(object sender, EventArgs e)
{
    if (listBox1.SelectedIndex != -1)
    {
       var myList = listbox1.SelectedItems as List<double>;
       return myList.Average();
    }
}
List doubleList=新列表();
私有无效btnGetAverage\u单击(对象发送者,事件参数e)
{
如果(listBox1.SelectedIndex!=-1)
{
var myList=listbox1.SelectedItems作为列表;
返回myList.Average();
}
}

将您的替身列表添加到您的
列表框中,如下所示:

listBox1.DataSource = doubleList;
然后,这将获得仅选定项目的平均值:

var average = listBox1.SelectedItems.Cast<double>().Average();
var average=listBox1.SelectedItems.Cast().average();

首先将列表框的SelectionMode属性设置为MultiSimple。然后试试这个代码

    double total = 0;
    for (int i = 0; i < listBox1.SelectedItems.Count; i++)
    {
        total += Double.Parse(listBox1.SelectedItems[i].ToString());
    }

    MessageBox.Show("The average is: " + total / listBox1.SelectedItems.Count);
双倍合计=0;
对于(int i=0;i
当前上下文中不存在listbox1错误,返回有错误我假设您可以在代码中访问listbox1,因为您已经在代码示例中检查SelectedIndex。我错了吗?我只是将这些值直接添加到listBox1中,因为我不知道如何将它们转换为double并从中计算它们。在从listboxBreaks中选择值之后,运行它时,您的代码将如何中断?当我测试它时,它工作得很好。另外,
listBox1
怎么不存在(将您的评论读给Yuval)?您在自己的代码中发布了它,并且您没有说该部件抛出了一个错误。它为您的部件说明了InvalidCastException。不,我发布的代码没有抛出错误他发布的代码中的listbox1正在抛出错误。