gpt4 book ai didi

c# - 如何使用 LINQ 获取日期范围内的平均值

转载 作者:行者123 更新时间:2023-11-30 20:01:04 25 4
gpt4 key购买 nike

我正在尝试确定是否可以在 LINQ to Objects 语句中完成以下操作。

我有一个字典,键为 DateTime(键是多天的值)和一个 double 值。我有太多数据无法绘制在图表上,因此想要每 5 分钟的平均值。

示例输入

01/01/2012 23:53    5
01/01/2012 23:54 2
01/01/2012 23:55 1
01/01/2012 23:56 3
01/01/2012 23:57 4
01/01/2012 23:58 5
01/01/2012 23:59 6
02/01/2012 00:00 2
02/01/2012 00:01 4
02/01/2012 00:02 5

预期输出

01/01/2012 23:55    3
02/01/2012 00:00 4.4

最佳答案

使用这个 helper方法:

static DateTime RoundToNearestInterval(DateTime dt, TimeSpan d)
{
int f=0;
double m = (double)(dt.Ticks % d.Ticks) / d.Ticks;
if (m >= 0.5)
f=1;
return new DateTime(((dt.Ticks/ d.Ticks)+f) * d.Ticks);
}

就这么简单

var result = from kvp in data
let key = RoundToNearestInterval(kvp.Key, TimeSpan.FromMinutes(5))
group kvp by key into g
select new { g.Key, Value = g.Average(x => x.Value) };

var result = data.GroupBy(kvp => RoundToNearestInterval(kvp.Key, TimeSpan.FromMinutes(5)), kvp => kvp.Value)
.Select(g => new { g.Key, Value = g.Average() });

LINQPad 示例:

void Main()
{
var tmp = new Dictionary<string, int>
{
{"01/01/2012 23:53", 5},
{"01/01/2012 23:54", 2},
{"01/01/2012 23:55", 1},
{"01/01/2012 23:56", 3},
{"01/01/2012 23:57", 4},
{"01/01/2012 23:58", 5},
{"01/01/2012 23:59", 6},
{"02/01/2012 00:00", 2},
{"02/01/2012 00:01", 4},
{"02/01/2012 00:02", 5}
};
var data = tmp.ToDictionary(d => DateTime.Parse(d.Key), d=>d.Value);

var result = from kvp in data
let key = RoundToNearestInterval(kvp.Key, TimeSpan.FromMinutes(5))
group kvp by key into g
select new {g.Key, Value = g.Average (x => x.Value) };

result.ToDictionary(r => r.Key, v => v.Value).Dump();
}

enter image description here

关于c# - 如何使用 LINQ 获取日期范围内的平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19652743/

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