Sum of TimeSpans in C#

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

    Here's what I tried and it worked:

    System.Collections.Generic.List collection = new List();
    MyObject mb = new MyObject();
    mb.TheDuration = new TimeSpan(100000);
    collection.Add(mb);
    mb.TheDuration = new TimeSpan(100000);
    collection.Add(mb);
    mb.TheDuration = new TimeSpan(100000);
    collection.Add(mb);
    var sum = (from r in collection select r.TheDuration.Ticks).Sum();
    Console.WriteLine( sum.ToString());
    //here we have new timespan that is sum of all time spans
    TimeSpan sumedup = new TimeSpan(sum);
    
    
    public class MyObject
    {
        public TimeSpan TheDuration { get; set; }
    }
    

提交回复
热议问题