Linq跳过并进入课程清单

时间:2018-11-07 12:16:42

标签: c# linq average

根据此堆栈问题:How to calculate the rolling average of a C# array list?

使用普通列表,您可以像这样对列表中的值进行取平均值:

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

我想对类列表的特定子集执行相同的操作:

public class Data_Raw
{
    public DateTime DateDataRaw { set; get; }
    public double PriceRaw { set; get; }
    public double PercentageReturnsRaw { set; get; }

    public Data_Raw(DateTime _dateDataRaw,double _priceRaw, double _percentageReturnsRaw)
    {
        DateDataRaw = _dateDataRaw;                     //1
        PriceRaw = _priceRaw;
        PercentageReturnsRaw = _percentageReturnsRaw;
    }
}

List<Data_Raw> myRawData = new List<Data_Raw>();

因此,现在我想在类列表myRawData中获得PriceRaw double数据的平均值。请帮助

编辑:

如果这些是myRawData列表的PriceRaw变量的数据:

myRawData[0].PriceRaw=2
myRawData[1].PriceRaw=3
myRawData[2].PriceRaw=4
myRawData[3].PriceRaw=5

如何获取最近三个PriceRaw值的平均值=(3 + 4 + 5)/ 3 =4。它仅在myRawData.Skip之后可用

如果我尝试将跳过附加到myRawData[].PriceRaw.Skip

,则跳过不可用

这个堆栈问题使我更接近,但无法弄清楚:Linq query a List of objects containing a list of object

2 个答案:

答案 0 :(得分:0)

只需在numList中选择所需的值(请参见第一行):

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

另一种可能的方式是:

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

答案 1 :(得分:0)

我认为,如果您使用理解语法,则对它进行管理会更容易。即:

void Main()
{
    List<Data_Raw> myRawData = new List<Data_Raw> {
       new Data_Raw(new DateTime(2018,1,1), 2, 1),
       new Data_Raw(new DateTime(2018,1,2), 3, 1),
       new Data_Raw(new DateTime(2018,1,3), 4, 1),
       new Data_Raw(new DateTime(2018,1,4), 5, 1),
       new Data_Raw(new DateTime(2018,1,5), 6, 1),
       new Data_Raw(new DateTime(2018,1,6), 7, 1),
       new Data_Raw(new DateTime(2018,1,7), 8, 1),
    };

    var groupSize = 3;
    var result = from i in Enumerable.Range(0, myRawData.Count() - (groupSize - 1))
                 let myGroup = myRawData.Skip(i).Take(groupSize)
                 select new
                 {
                     Values = string.Join(",", myGroup.Select(rd => rd.PriceRaw.ToString())),
                     Average = myGroup.Average(rd => rd.PriceRaw)
                 };
}

public class Data_Raw
{
    public DateTime DateDataRaw { set; get; }
    public double PriceRaw { set; get; }
    public double PercentageReturnsRaw { set; get; }

    public Data_Raw(DateTime _dateDataRaw, double _priceRaw, double _percentageReturnsRaw)
    {
        DateDataRaw = _dateDataRaw;                     //1
        PriceRaw = _priceRaw;
        PercentageReturnsRaw = _percentageReturnsRaw;
    }
}