获取可观察集合元素数据的平均值
我有一个包含 60 个元素的 observablecollection,每个元素包含数字(双精度)数据。我想得到 60 个元素的平均值((60 个元素的总和)/60)。知道我该怎么做吗?
这是我的代码:
public class MainWindow : Window
{
DispatcherTimer timer = new DispatcherTimer();
double i = 0;
ObservableCollection<KeyValuePair<double, double>> Power = new ObservableCollection<KeyValuePair<double, double>>();
public MainWindow()
{
InitializeComponent();
timer.Interval = new TimeSpan(0, 0, 1); // per 5 seconds, you could change it
timer.Tick += new EventHandler(timer_Tick);
timer.IsEnabled = true;
}
Random random = new Random(DateTime.Now.Millisecond);
void timer_Tick(object sender, EventArgs e)
{
Power.Add(new KeyValuePair<double, double>(i, random.NextDouble() ));
i += 5;
}
}
I have an observablecollection containing 60 elements, each containing data of numbers(double). I would like to get the average of the 60 elements( (total sum of 60 elements)/60). Any idea how I can go about it?
Here is my code:
public class MainWindow : Window
{
DispatcherTimer timer = new DispatcherTimer();
double i = 0;
ObservableCollection<KeyValuePair<double, double>> Power = new ObservableCollection<KeyValuePair<double, double>>();
public MainWindow()
{
InitializeComponent();
timer.Interval = new TimeSpan(0, 0, 1); // per 5 seconds, you could change it
timer.Tick += new EventHandler(timer_Tick);
timer.IsEnabled = true;
}
Random random = new Random(DateTime.Now.Millisecond);
void timer_Tick(object sender, EventArgs e)
{
Power.Add(new KeyValuePair<double, double>(i, random.NextDouble() ));
i += 5;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用
Average()
LINQ-to-Objects扩展方法:You can use the
Average()
LINQ-to-Objects extension method: