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
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;
if (list.Count > 0)
{
textBox2.Text = list.Average().ToString();
}
if (list.Count > 1)
{
double average = list.Average();
textBox2.Text = average.ToString();
rotorSpeed.Stop();
}
This works just fine. Thanks!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.