TimeSpan Sum

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

Description

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

Details

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

Double click on the code to select all.

 

;