Is t开发者_运维百科here 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.
C#:
TimeSpan sum = times.Aggregate((t1, t2) => t1.Add(t2));
VB.NET:
Dim sum As TimeSpan = times.Aggregate(Function(t1, t2) t1.Add(t2))
You have the answer there - just use TimeSpan.Add.
You can do the collection using LINQ's Enumerable.Aggregate if you want to avoid the loop:
Dim sum as TimeSpan
sum = times.Aggregate(Function(ByVal current, ByVal ts) ts.Add(current) )
Edit: If you want an extension method to do this, you could do:
''
<Extension()>
Public Function Aggregate(ByVal IEnumerable(Of TimeSpan) times) As TimeSpan
Return times.Aggregate(Function(ByVal current, ByVal ts) ts.Add(current) )
End Function
Sure.
Enumerable.Aggregate
just needs a Func<T, T, T>
-- something that takes two T
objects and aggregates them in some way to product a new T
. So you can go with Yuriy's method:
// The + operator is defined for TimeSpan, so you're fine just using that.
TimeSpan sum = times.Aggregate((t1, t2) => t1 + t2);
Or, you can also do something like what Tim Coker suggested, using the Enumerable.Sum
extension method:
TimeSpan sum = TimeSpan.FromTicks(times.Sum(t => t.Ticks));
Update: Here are the VB.NET equivalents:
Dim sum = times.Aggregate(Function(t1, t2) t1 + t2)
Dim sum = TimeSpan.FromTicks(times.Sum(Function(t) t.Ticks))
You can use the Sum
method to add the Ticks
value from each 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 t As New TimeSpan(times.Sum(Function(t) t.Ticks))
You need to sum TimeSpan.Ticks
then create a new TimeSpan
with that value
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)
精彩评论