C# 查找 TimeSpan 集合的平均值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8847679/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 04:46:38  来源:igfitidea点击:

Find average of collection of TimeSpans

c#averagetimespan

提问by hs2d

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.

我收集了 TimeSpans,它们代表执行任务所花费的时间。现在我想找出在该任务上花费的平均时间。这应该很容易,但由于某种原因,我没有得到正确的平均值。

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());
}

采纳答案by 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);

回答by George Duckett

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.

请注意,您的方法返回一个Nullable,但不需要,除非您想在源列表为空时返回 null,在这种情况下只需先进行单独检查。

回答by 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)