gpt4 book ai didi

C# linq 根据以前的数据创建一个与函数相关的新项目

转载 作者:太空宇宙 更新时间:2023-11-03 12:41:21 26 4
gpt4 key购买 nike

List<History> data = new List<History>(){   
new History() {Symbol="a", Close = 1.0m, Date = new DateTime(2016, 2, 1) },
new History() {Symbol="a", Close = 1.2m, Date = new DateTime(2016, 2, 2) },
new History() {Symbol="a", Close = 1.3m, Date = new DateTime(2016, 2, 3) },
new History() {Symbol="b", Close = 1.2m, Date = new DateTime(2016, 2, 1) },
new History() {Symbol="b", Close = 1.2m, Date = new DateTime(2016, 2, 2) },
new History() {Symbol="b", Close = 1.3m, Date = new DateTime(2016, 2, 3) },
};

var StockGroupList = data
.GroupBy(o => o.Symbol)
.OrderBy(o => o.Key)
.ToList();

我想创建一个新的列表

select new { Symbol, Close, Date, Vol};

此处 Vol 是两天的标准偏差,例如 Symbol="a"Vol at 2016, 2, 3close 的函数,适用于 2016, 2, 32016, 2, 2。此外,第一天的Vol(例如2016, 2, 1)默认为Vol = 0

预期输出:

List<dynamic> NewData = new List<dynamic>
{
new { Symbol = "a", Close = 1.0m, Date = new DateTime(2016, 2, 1), Vol = 0 },
new { Symbol = "a", Close = 1.0m, Date = new DateTime(2016, 2, 2), Vol = SD(Close of 2016, 2, 1, Close of 2016, 2, 2) },
new { Symbol = "a", Close = 1.0m, Date = new DateTime(2016, 2, 3), Vol = SD(Close of 2016, 2, 2, Close of 2016, 2, 3) },
......
};

你可以把SD(x,y)看成一个给定的函数,简单地说SD(x,y) = x+y。此外,如果 SD 的参数是 List 则说 List[Close of 2016, 2, 2, Close of 2016, 2, 3)],那我该怎么办?

如果 SD 是以下形式

decimal OneStdDev = (decimal)(new DescriptiveStatistics(data.Select(o => (double)o.Close)).StandardDeviation);

我该怎么办?

最佳答案

我怀疑你在这种情况下是否需要分组,如果我理解你的问题,你想计算当前和以前历史记录之间的 SD

您可以使用 Linq 扩展方法来做到这一点。

var results = data          
.Take(1)
.Select(x=>new {x.Symbol, x.Close, x.Date, Vol = 0.0m})
.Concat(data.Zip(data.Skip(1), (first,second) =>
new
{
second.Symbol,
second.Close,
second.Date,
Vol = first.Close + second.Close // Use whatever logic you want.
}
));

输出:

Symbol =a, Close=1.0, Date=2/1/2016 12:00:00 AM, Vol = 0.0
Symbol =a, Close=1.2, Date=2/2/2016 12:00:00 AM, Vol = 2.2
Symbol =a, Close=1.3, Date=2/3/2016 12:00:00 AM, Vol = 2.5
Symbol =b, Close=1.2, Date=2/1/2016 12:00:00 AM, Vol = 2.5
Symbol =b, Close=1.2, Date=2/2/2016 12:00:00 AM, Vol = 2.4
Symbol =b, Close=1.3, Date=2/3/2016 12:00:00 AM, Vol = 2.5

检查这个Demo

关于C# linq 根据以前的数据创建一个与函数相关的新项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38908997/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com