开发者

Why isn't my TimeSpan.Add() working?

There has to be an easy answer:

var totalTime = TimeSpan.Zero;

foreach (var timesheet in timeSheets)
{
   //assume "time" is a correct, positive TimeSpan
   var time = timesheet.EndTime - timesheet.开发者_运维知识库StartTime;
   totalTime.Add(time);
}

There's only one value in the list timeSheets and it is a positive TimeSpan (verified on local inspection).


TimeSpans are value types. Try:

totalTime = totalTime.Add(time)


This is a common mistake. TimeSpan.Add returns a new instance of TimeSpan.


totalTime = totalTime.Add(time)


TimeSpans are value types and can use the += operator similar to integral and floating point numeric types. I find the += operator neat to use in this situation which is the same as writing x = x + y.

var totalTime = TimeSpan.Zero;

foreach (var timesheet in timeSheets)
{
   totalTime += (timesheet.EndTime - timesheet.StartTime);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜