Sum of TimeSpans in C#

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

    I put this in a class to add an extension method to a collection of timespans:

    public static class Extensions:
    {
        public static TimeSpan TotalTime(this IEnumerable TheCollection)
        {
            int i = 0;
            int TotalSeconds = 0;
    
            var ArrayDuration = TheCollection.ToArray();
    
            for (i = 0; i < ArrayDuration.Length; i++)
            {
                TotalSeconds = (int)(ArrayDuration[i].TotalSeconds) + TotalSeconds;
            }
    
            return TimeSpan.FromSeconds(TotalSeconds);
        }
    }
    

    So now, I can write TotalDuration = (my LINQ query that returns a collection of timespan).TotalTime();

    Voila!

提交回复
热议问题