如何计算给定列表的平均值,其内容如下所述:
06:56
06:58
06:55
06:54
06:54
06:53
06:55
06:53
06:58
06:54
06:58
06:55
06:54
06:50
06:54
06:57
有什么想法?!?
答案 0 :(得分:9)
var times = new List<string>
{
"06:56",
"06:58",
"06:55",
"06:54",
"06:54",
"06:53",
"06:55",
"06:53",
"06:58",
"06:54",
"06:58",
"06:55",
"06:54",
"06:50",
"06:54",
"06:57"
};
var average = times
.Select(TimeSpan.Parse)
.Average(x => x.TotalMilliseconds);
var averageTime = TimeSpan.FromMilliseconds(average);
答案 1 :(得分:2)
将值转换为 TimeSpan 。您可以直接将输出作为正确的数据类型进行平均。
<强>附录强>
从@gabba添加答案,提供字符串列表和上面使用滴答的链接,您可以通过这种方式计算平均值:
TimeSpan average = new TimeSpan(Convert.ToInt64(times.Average(x => TimeSpan.Parse(x).Ticks)));
结果值当然是相同的:06:54:52.500