Question

So this is how far I have gotten I am not really sure. So I populated my listbox1 with values such as 1.2, 1.3 So how do I add all the selected values of my listbox and caculate the average? If you could help me I be very thankful.

    List<double> doubleList = new List<double>();
    private void btnGetAverage_Click(object sender, EventArgs e)
    {
        if (listBox1.SelectedIndex != -1)
        {
        }
    }
Was it helpful?

Solution

First make the SelectionMode property of your listbox as MultiSimple. Then try this code.

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

OTHER TIPS

You can you the Average method:

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

Add your list of doubles to your ListBox like this:

listBox1.DataSource = doubleList;

Then this will get you the average of only selected items:

var average = listBox1.SelectedItems.Cast<double>().Average();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top