Sum of TimeSpans in C#

前端 未结 8 1029
执笔经年
执笔经年 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:41

    Once you understand that timespans can't be summed and know to use Ticks, it seems to me that this extension to just convert a long into a timespan looks more linq-ee. I believe it lets the reader have a more readable view of the operation:

    var times = new[] { new TimeSpan(0, 10, 0), new TimeSpan(0, 20, 0), new TimeSpan(0, 30, 0) };
    
    times.Sum(p => p.Ticks)
         .ToTimeSpan();      // output: 01:00:00
         
    

    Here is the one extension:

    public static class LongExtensions
    {
        public static TimeSpan ToTimeSpan(this long ticks)
            => new TimeSpan(ticks);
    }
    

提交回复
热议问题