TimeSpan Average

/// <summary>
/// Calculates the average of the given timeSpans.
/// </summary>
public static TimeSpan Average(this IEnumerable<TimeSpan> timeSpans)
{
	IEnumerable<long> ticksPerTimeSpan = timeSpans.Select(t => t.Ticks);
	double averageTicks = ticksPerTimeSpan.Average();
	long averageTicksLong = Convert.ToInt64(averageTicks);

	TimeSpan averageTimeSpan = TimeSpan.FromTicks(averageTicksLong);

	return averageTimeSpan;
}
Example:
List<TimeSpan> timeSpans = new List<TimeSpan>();
timeSpans.Add(TimeSpan.FromHours(1));
timeSpans.Add(TimeSpan.FromHours(2));
timeSpans.Add(TimeSpan.FromHours(3));
TimeSpan average = timeSpans.Average();// will be 02:00

Description

C# LINQ has no Average method for TimeSpan. Here it is!

Details

  • Author: Joseph K
  • Submitted on: 12/5/2017 11:10:49 AM
  • Language: C#
  • Type: TimeSpan
  • Views: 49

Double click on the code to select all.

 

;