14

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

Lauren Rutledge
  • 1,195
  • 5
  • 18
  • 27
rltcounter221
  • 183
  • 1
  • 1
  • 10

3 Answers3

23

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;
Rahul
  • 76,197
  • 13
  • 71
  • 125
  • 6
    Why `0.0`? Is it your opinion that one can silently use zero? Another option would be `list.Count > 0 ? list.Average() : double.NaN`. The average of an empty sequence can be said to be `0.0 / 0.0`, in a sense. – Jeppe Stig Nielsen Sep 24 '16 at 18:03
5
if (list.Count > 0)
{
    textBox2.Text = list.Average().ToString();
}
TigOldBitties
  • 1,331
  • 9
  • 15
1
if (list.Count > 1)
{
    double average = list.Average();
    textBox2.Text = average.ToString();
    rotorSpeed.Stop();
}

This works just fine. Thanks!

Alex
  • 14,104
  • 11
  • 54
  • 77
rltcounter221
  • 183
  • 1
  • 1
  • 10