Find average of collection of TimeSpans

蹲街弑〆低调 提交于 2019-11-27 12:39:35

问题


I have collection of TimeSpans, they represent time spent doing a task. Now I would like to find the average time spent on that task. It should be easy but for some reason I'm not getting the correct average.

Here's my code:

private TimeSpan? GetTimeSpanAverage(List<TimeSpan> sourceList)
{
    TimeSpan total = default(TimeSpan);

    var sortedDates = sourceList.OrderBy(x => x);

    foreach (var dateTime in sortedDates)
    {
        total += dateTime;
    }
    return TimeSpan.FromMilliseconds(total.TotalMilliseconds/sortedDates.Count());
}

回答1:


You can use the Average extension method:

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

return new TimeSpan(longAverageTicks);



回答2:


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.




回答3:


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)


来源:https://stackoverflow.com/questions/8847679/find-average-of-collection-of-timespans

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