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

TimeSpan Sum

C# LINQ has no Sum method for TimeSpan. Here it is1

Source

/// <summary>
/// Calculates the sum of the given timeSpans.
/// </summary>
public static TimeSpan Sum(this IEnumerable<TimeSpan> timeSpans)
{
	TimeSpan sumTillNowTimeSpan = TimeSpan.Zero;

	foreach (TimeSpan timeSpan in timeSpans)
	{
		sumTillNowTimeSpan += timeSpan;
	}

	return sumTillNowTimeSpan;
}

Example

List<TimeSpan> timeSpans = new List<TimeSpan>();
timeSpans.Add(TimeSpan.FromHours(1));
timeSpans.Add(TimeSpan.FromHours(2));
timeSpans.Add(TimeSpan.FromHours(3));
TimeSpan sum = timeSpans.Sum();// will be 06:00

Author: Joseph K

Submitted on: 5 dec 2017

Language: C#

Type: TimeSpan

Views: 3045