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.Tic开发者_如何学运维k += 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;
}
}
You can use the Average()
LINQ-to-Objects extension method:
var avg = Power.Average(x => x.Value);
精彩评论