Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Average value of list

Tags:

c#

list

stopwatch

I want to make code that will on the first click start rotorSpeed stopwatch then on the second click add rotorSpeed.ElapsedMilliseconds to list. On the second click resets stopwatch and starts timing again, then on the third click again adds rotorSpeed.ElapsedMilliseconds to list. There are no errors in the code, but when I debug it, I get an error on double average = list.Average();

Stopwatch rotorSpeed = new Stopwatch(); List<double> list = new List<double>();

private void button1_Click(object sender, EventArgs e)
{
    i++;
    //Getting rotor speed
    if (i != 2)
    {               
        if (rotorSpeed.IsRunning)
        {
            rotorSpeed.Stop();
            list.Add(rotorSpeed.ElapsedMilliseconds);
            rotorSpeed.Start();                   
        }
        else
        {
            rotorSpeed.Reset();
            rotorSpeed.Start();
        }
    }

    double average = list.Average();
    textBox2.Text = average.ToString();
}

This is the error I get:

An unhandled exception of type 'System.InvalidOperationException' occurred in >System.Core.dll

Additional information: Sequence contains no elements

like image 673
rltcounter221 Avatar asked Sep 24 '16 17:09

rltcounter221


3 Answers

Your list is empty and so calling Average() on it throwing exception. Change the below line

double average = list.Average();

to

double average = list.Count > 0 ? list.Average() : 0.0;
like image 192
Rahul Avatar answered Sep 23 '22 03:09

Rahul


if (list.Count > 0)
{
    textBox2.Text = list.Average().ToString();
}
like image 20
TigOldBitties Avatar answered Sep 26 '22 03:09

TigOldBitties


if (list.Count > 1)
{
    double average = list.Average();
    textBox2.Text = average.ToString();
    rotorSpeed.Stop();
}

This works just fine. Thanks!

like image 26
rltcounter221 Avatar answered Sep 23 '22 03:09

rltcounter221