Search code examples
.netextension-methodsaggregatetimespanaccumulate

Sum TimeSpan array with a one-liner?


Is there a way to aggregate multiple aggregates to 1 time span?

Dim times = { 
  New TimeSpan(1, 0, 0),
  New TimeSpan(1, 10, 0),
  New TimeSpan(1, 50, 0),
  New TimeSpan(0, 20, 0),
  New TimeSpan(0, 10, 0)
}

Dim sum As New TimeSpan
For Each ts In times
  sum = sum.Add(ts)
Next

'That's what I desire:
sum = times.Sum
sum = times.Aggregate

I am looking for some built in capability I don't know about.

Update Please read my comment on Reed Copsey's answer.


Solution

  • C#:

    TimeSpan sum = times.Aggregate((t1, t2) => t1.Add(t2));
    

    VB.NET:

    Dim sum As TimeSpan = times.Aggregate(Function(t1, t2) t1.Add(t2))