Find average of collection of TimeSpans

a 夏天 提交于 2019-11-28 20:03:28
vc 74

You can use the Average extension method:

double doubleAverageTicks = sourceList.Average(timeSpan => timeSpan.Ticks);
long longAverageTicks = Convert.ToInt64(doubleAverageTicks);

return new TimeSpan(longAverageTicks);
var average = new TimeSpan(sourceList.Select(ts => ts.Ticks).Average());

Note, your method returns a Nullable, but doesn't need to, unless you want to return null if the source list is empty, in which case just do a separate check first.

V4Vendetta

In Addition to the above answer, I would suggest you take an average on the Seconds or MilliSeconds level (depending on what you require)

sourceList.Average(timeSpan => timeSpan.ToTalMilliseconds)

Now using this value you could arrive at the new TimeSpan using

TimeSpan avg = TimeSpan.FromMilliseconds(double value here)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!