I have a collection of objects that include a TimeSpan variable:
MyObject
{
TimeSpan TheDuration { get; set; }
}
I want to use LINQ to
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;
}
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)