I have a collection of objects that include a TimeSpan variable:
MyObject
{
TimeSpan TheDuration { get; set; }
}
I want to use LINQ to sum those times.
Of course, (from r in MyCollection select r.TheDuration).Sum(); doesn’t work!
I’m thinking of changing the datatype of TheDuration to an int and then summing it and converting the sum to a TimeSpan. That will be messy because each TheDuration in my collection is used in as a timespan somewhere else.
Any suggestion on this summation?
Unfortunately, there isn’t a an overload of
Sumthat accepts anIEnumerable<TimeSpan>. Additionally, there’s no current way of specifying operator-based generic constraints for type-parameters, so even thoughTimeSpanis “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
TimeSpanagain. The ideal property for this isTimeSpan.Ticks, which round-trips accurately. But it’s not necessary to change the property-type on your class at all; you can just project:Alternatively, if you want to stick to the TimeSpan’s
+operator to do the summing, you can use theAggregateoperator: