12 February, 2010
0 Comments
1 category
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
Tags: LINQ
Category: Uncategorized
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));