使用单线程的Sum TimeSpan数组?

时间:2010-07-13 16:37:17

标签: .net extension-methods aggregate timespan accumulate

有没有办法将多个聚合聚合到一个时间跨度?

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

我正在寻找一些我不知道的内置功能。<​​/ p>

更新 请阅读我对Reed Copsey's answer的评论。

5 个答案:

答案 0 :(得分:12)

C#:

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

VB.NET:

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

答案 1 :(得分:2)

你有答案 - 只需使用TimeSpan.Add

如果你想避免循环,可以使用LINQ的Enumerable.Aggregate进行收集:

Dim sum as TimeSpan
sum = times.Aggregate(Function(ByVal current, ByVal ts) ts.Add(current) )

编辑:如果您想要一个扩展方法来执行此操作,您可以执行以下操作:

''
<Extension()> 
Public Function Aggregate(ByVal IEnumerable(Of TimeSpan) times) As TimeSpan
     Return times.Aggregate(Function(ByVal current, ByVal ts) ts.Add(current) )
End Function

答案 2 :(得分:1)

不确定

Enumerable.Aggregate只需要Func<T, T, T> - 需要两个T个对象并以某种方式聚合它们以生成新的T。所以你可以使用Yuriy's method

// The + operator is defined for TimeSpan, so you're fine just using that.
TimeSpan sum = times.Aggregate((t1, t2) => t1 + t2);

或者,您也可以使用what Tim Coker suggested扩展程序 Enumerable.Sum执行某些操作:

TimeSpan sum = TimeSpan.FromTicks(times.Sum(t => t.Ticks));

更新:这是VB.NET的等价物:

Dim sum = times.Aggregate(Function(t1, t2) t1 + t2)

Dim sum = TimeSpan.FromTicks(times.Sum(Function(t) t.Ticks))

答案 3 :(得分:1)

您可以使用Sum方法添加每个Ticks的{​​{1}}值:

TimeSpan

答案 4 :(得分:0)

您需要对TimeSpan.Ticks求和,然后使用该值

创建新的TimeSpan
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 sumTicks As Long = 0
For Each ts In times
    sumTicks += ts.Ticks
Next

Dim sum As New TimeSpan(sumTicks)