Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find average of collection of TimeSpans

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()); } 
like image 382
hs2d Avatar asked Jan 13 '12 08:01

hs2d


People also ask

How do you find the average TimeSpan?

So, to calculate average, you will need to use TotalMiliseconds property of TimeSpan. To determine max and min value, simple compare is enough.

How to get average of TimeSpan c#?

var average = new TimeSpan(sourceList. Select(ts => ts. Ticks).


2 Answers

You can use the Average overload that takes a collection of long in parameter:

double doubleAverageTicks = sourceList.Average(timeSpan => timeSpan.Ticks); long longAverageTicks = Convert.ToInt64(doubleAverageTicks);  return new TimeSpan(longAverageTicks); 
like image 180
vc 74 Avatar answered Oct 06 '22 00:10

vc 74


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.

like image 40
George Duckett Avatar answered Oct 06 '22 00:10

George Duckett