Sum of TimeSpans in C#

Unfortunately, there isn’t a an overload of Sum that accepts an IEnumerable<TimeSpan>. Additionally, there’s no current way of specifying operator-based generic constraints for type-parameters, so even though TimeSpan is “natively” summable, that fact can’t be picked up easily by generic code.

One option would be to, as you say, sum up an integral-type equivalent to the timespan instead, and then turn that sum into a TimeSpan again. The ideal property for this is TimeSpan.Ticks, which round-trips accurately. But it’s not necessary to change the property-type on your class at all; you can just project:

var totalSpan = new TimeSpan(myCollection.Sum(r => r.TheDuration.Ticks));

Alternatively, if you want to stick to the TimeSpan’s + operator to do the summing, you can use the Aggregate operator:

var totalSpan = myCollection.Aggregate
                (TimeSpan.Zero, 
                (sumSoFar, nextMyObject) => sumSoFar + nextMyObject.TheDuration);

Leave a Comment