Average value of list

rltcounter221 picture rltcounter221 · Sep 24, 2016 · Viewed 42.8k times · Source

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

Answer

Rahul picture Rahul · Sep 24, 2016

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;