0 Comments

If you want to sum TimeSpan properties in LINQ with C#, use:

            List<TimeSpan> list = new List<TimeSpan>             {
                new TimeSpan(1),
                new TimeSpan(2),
                new TimeSpan(3)
            };

            // TimeSpan.Zero is the initial offset, in this case 0 ticks
            // subtotal is used to sum to items in the list
            // t is the current item in the list
            TimeSpan total = list.Aggregate(TimeSpan.Zero, (subtotal, t) => subtotal.Add(t));

            Console.WriteLine(total.Ticks);

            // Result: 6

 

 

Thanks to: http://stackoverflow.com/questions/970178/c-how-to-use-the-enumerable-aggregate-method

One Reply to “How to sum TimeSpan in LINQ with C#

  1. TimeSpan holds its value in a long field for the ticks. So working with ticks should be very effective. To aggregate TimeSpan values you can sum the ticks of the list entries and create a new TimeSpan with the sum.

    TimeSpan total = new TimeSpan(list.Sum(t => t.Ticks));

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Posts

Map network drive in C#

// Create network drive mapping System.Diagnostics.Process.Start("net.exe", @"use K: ""\\my.server.com\Websites\Mail"" /user:MyDomain\admin…