开发者

Getting the average of observable collection element data

开发者 https://www.devze.com 2023-04-13 07:48 出处:网络
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 g

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号