ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

TimeSpan Average

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

Source

/// <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

Author: Joseph K

Submitted on: 5 dec. 2017

Language: C#

Type: TimeSpan

Views: 8261