Encontrar promedio de la colección de tiempos de espera


Tengo una colección de tiempos, representan el tiempo dedicado a hacer una tarea. Ahora me gustaría encontrar el tiempo promedio dedicado a esa tarea. Debería ser fácil, pero por alguna razón no estoy obteniendo el promedio correcto.

Aquí está mi código:

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());
}
Author: wonea, 2012-01-13

3 answers

Puede usar el Sobrecarga promedio que toma una colección de largo en el parámetro.

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

return new TimeSpan(longAverageTicks);
 80
Author: vc 74,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-10-21 12:08:49
var average = new TimeSpan(sourceList.Select(ts => ts.Ticks).Average());

Tenga en cuenta que su método devuelve un Nullable, pero no es necesario, a menos que desee devolver null si la lista fuente está vacía, en cuyo caso solo haga una comprobación por separado primero.

 12
Author: George Duckett,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-01-13 08:23:30

Además de la respuesta anterior, le sugeriría que tome un promedio en el nivel de Segundos o milisegundos (dependiendo de lo que necesite)

sourceList.Average(timeSpan => timeSpan.ToTalMilliseconds)

Ahora usando este valor puedes llegar al nuevo intervalo de tiempo usando

TimeSpan avg = TimeSpan.FromMilliseconds(double value here)
 3
Author: V4Vendetta,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-05 09:35:03