Sum of TimeSpans in C#

前端 未结 8 996
执笔经年
执笔经年 2020-11-29 06:01

I have a collection of objects that include a TimeSpan variable:

MyObject
{ 
    TimeSpan TheDuration { get; set; }
}

I want to use LINQ to

8条回答
  •  离开以前
    2020-11-29 06:51

    Unfortunately, there isn't a an overload of Sum that accepts an IEnumerable. 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);
    

提交回复
热议问题