Question

I have a function that calculates the total working hours by adding TtimeSpans. I tried to search through the web and found something TimeSpan.Add().

Here is some sample of my code:

TimeSpan TotalWorkHours = new TimeSpan(0,0,0);
List<TimeSpan> Interval = new List<TimeSpan>();

Interval.Add(TimeSpan.Parse("04:20:07"));
Interval.Add(TimeSpan.Parse("03:59:49"));

//Having a looping to Add in the Interval and combine the total work hours

for(int i = 0; i < Interval.count; i++)
{
    if(i == 0)
       TotalWorkHours = Interval[i];       
    else
       //This section will always add in "00:00:00"
       TotalWorkHours.Add(Interval[i]);
} 

However, the resulting timespan alwys is 00:00:00. Where does it go wrong?

Était-ce utile?

La solution

You're calling Add, but not using the result at all. Add doesn't change the value - it returns a new value. You want:

TotalWorkHours = TotalWorkHours.Add(Interval[i]);

Or more idiomatically, IMO:

TotalWorkHours += Interval[i];

Or even more idiomatically, to my mind:

// Note the casing of the variable names to follow conventions,
// and the fact that "intervals" is plural because it contains
// more than one interval.   
List<TimeSpan> intervals = ...;
var totalWorkHours = TimeSpan.Zero;
foreach (var interval in intervals)
{
    totalWorkHours += interval;
}

Or even just use LINQ aggregation:

var totalWorkHours = intervals.Aggregate(TimeSpan.Zero, (x, y) => x + y);

Autres conseils

Timespan is immutable. Any method that looks like it alters the state actually returns a new instance with the adjstment made. Just change your code to:

TotalWorkHours = TotalWorkHours.Add(Interval[i]);
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top