Sum of TimeSpans in C#

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

    You can use .Aggregate rather than .Sum, and pass it a timespan-summing function that you write, like this:

        TimeSpan AddTimeSpans(TimeSpan a, TimeSpan b)
        {
            return a + b;
        }
    
    0 讨论(0)
  • 2020-11-29 07:02

    This works well (code based on Ani's answer)

    public static class StatisticExtensions
    {    
        public static TimeSpan Sum<TSource>(this IEnumerable<TSource> source, Func<TSource, TimeSpan> selector)
        {
            return source.Select(selector).Aggregate(TimeSpan.Zero, (t1, t2) => t1 + t2);
        }
    }
    

    Usage :

    If Periods is a list of objects with a Duration property

    TimeSpan total = Periods.Sum(s => s.Duration)
    
    0 讨论(0)
提交回复
热议问题