作者:qw874515 | 来源:互联网 | 2022-12-10 12:29
我有一个List,我需要通过Created计算每天的平均值.如何优雅地迭代列表中显示的每一天的列表?每天可能存在空白,每天都有不同数量的物体.
例如,值可能是这样的:
public class MyObject
{
public double Value { get; set; }
public DateTime Created { get; set; }
}
{ Value: 1, Created: 2018-07-01 12:00:00 }
{ Value: 4, Created: 2018-07-01 20:00:00 }
{ Value: 2, Created: 2018-07-03 12:00:00 }
{ Value: 3, Created: 2018-07-04 09:00:00 }
{ Value: 2, Created: 2018-07-04 11:00:00 }
{ Value: 6, Created: 2018-07-04 12:00:00 }
{ Value: 5, Created: 2018-07-06 16:00:00 }
{ Value: 3, Created: 2018-07-06 11:00:00 }
我可以去做这样的事......
List items = itemsfrombackend;
DateTime beginDay = items.First().Created;
DateTime endDay = items.Last().Created;
for (DateTime day = beginDay; day <= endDay; day.AddDays(1))
{
// if items contains any matching objects calculate avg
}
但是想用更少的ifs找到一种更简单的方法
1> fubo..:
我会GroupBy()
结合使用Average()
var result = items.GroupBy(x => x.Created.Date)
.Select(x => new { Created = x.Key, Avg = x.Average(y => y.Value) });