如何计算C#数组列表的滚动平均值? [英] How to calculate the rolling average of a C# array list?

查看:398
本文介绍了如何计算C#数组列表的滚动平均值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试计算数组列表中每四个值的滚动平均值,并将这些值添加到单独的数组列表中.我原来的数组列表称为numlist,它包含的值从1到9

I'm trying to calculate the rolling averages of every four values in an array list and add those values to a separate array list. My original array list is called numlist and it contains values from 1 to 9

List<int> numlist = new List<int>();

numlist.Add(1);
numlist.Add(2);
numlist.Add(3);
numlist.Add(4);
numlist.Add(5);
numlist.Add(6);
numlist.Add(7);
numlist.Add(8);
numlist.Add(9);

当计算滚动平均值时,应采用以下方式:

When it calculates rolling averages, it should do it in an way like this:

第一平均值=(1 + 2 + 3 + 4)/4

first average = (1+2+3+4)/4

第二平均=(2 + 3 + 4 + 5)/4

second average = (2+3+4+5)/4

第三平均值=(3 + 4 + 5 + 6)/4

third average = (3+4+5+6)/4

以此类推

第二个数组列表

List<double> avelist = new List<double>();

应包含这些值

{2.5, 3.5, 4.5, 5.5, 6.5, 7.5}

我该如何实现?

推荐答案

您可以像这样使用LINQ:

You can use LINQ like this:

List<double> averages = Enumerable.Range(0, numlist.Count - 3).
                              Select(i => numlist.Skip(i).Take(4).Average()).
                              ToList();

在您的示例中,它从i = 0i = 5,并从索引为i的列表中取出4个元素,并计算它们的平均值.

In your example, this goes from i = 0 to i = 5 and takes 4 elements from the list starting at index i and calculates their average.

您可以这样输出结果:

Console.WriteLine(string.Join(" ", averages));


对于滚动平均值,具有宽度"变量的方法可能类似于:


A method with a variable "width" for the rolling average could look like:

public List<double> RollingAverage(List<int> source, int width)
{
    return Enumerable.Range(0, 1 + numlist.Count - width).
                              Select(i => numlist.Skip(i).Take(width).Average()).
                              ToList();
}


文档:


Documentation:

  • Enumerable.Range
  • Enumerable.Select
  • Enumerable.Skip
  • Enumerable.Take
  • Enumerable.Average

这篇关于如何计算C#数组列表的滚动平均值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆