2016-09-24 382 views
0

我想做一个代码,将在第一次点击开始rotorSpeed秒表,然后在第二次点击添加rotorSpeed.ElapsedMillisecondslist。在第二次点击重置秒表并重新开始计时,然后在第三次点击再次将rotorSpeed.ElapsedMilliseconds添加到list。 有在代码中没有错误,但是当我调试它,我得到double average = list.Average();在C#中列表的平均值

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

错误这是我的错误:

类型的未处理的异常“系统。 InvalidOperationException'发生在> System.Core.dll

附加信息:序列不包含元素

+0

你得到的错误是什么? – pavnik

+4

这可能是因为你试图在第一次点击后没有任何元素的列表的“平均”。你得到的例外是什么? – MarcinJuraszek

+1

@pavnik在System.Core.dll中发生未处理的异常类型'System.InvalidOperationException' 附加信息:Sequence不包含元素 – rltcounter221

回答

2
if (list.Count > 0) 
{ 
    textBox2.Text = list.Average().ToString(); 
} 
+0

count应该大于等于为1. –

+0

为什么?平均1个元素没有任何意义。 LE:除非这是在文本框中显示的内容。在这种情况下,我想你会是对的:) – TigOldBitties

+0

如果列表计数为1,文本框将不会填充。 –

2

list是空的,所以调用Average()它抛出异常。下面的线

double average = list.Average(); 

更改为

double average = list.Count > 0 ? list.Average() : 0.0; 
+1

为什么'0.0'?你认为可以默默使用零?另一个选项是'list.Count> 0? list.Average():double.NaN'。从某种意义上说,空序列的平均值可以说是“0.0/0.0”。 –

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

这一切正常。谢谢!