获取可观察集合元素数据的平均值

时间:2011-10-13 15:51:51

标签: c# wpf observablecollection

我有一个包含60个元素的observablecollection,每个元素都包含数字数据(double)。我想得到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;

    }
}

1 个答案:

答案 0 :(得分:3)

您可以使用Average() LINQ-to-Objects扩展方法:

var avg = Power.Average(x => x.Value);