如何从多个日期计算秒数的时间?

时间:2017-01-16 06:19:44

标签: c# indexoutofboundsexception

我在列表集合中有一些日期,如下所示

new List<EventItemModel>()
{
 new EventItemModel() {DateTime = new DateTime(2017,1,1,10,0,0), Event = EventType.Enter},
 new EventItemModel() {DateTime = new DateTime(2017,1,1,10,30,0), Event = EventType.Pass},
 new EventItemModel() {DateTime = new DateTime(2017,1,1,11,30,0), Event = EventType.Leave},
}

从唱这个函数我计算从日期集合开始的秒数

 public static double GetTotalDurationFor(this Enumerable<EventItemModel> lst)
    {
        var selectedEmployeDayinout = lst.OrderBy(d => d.DateTime).ToList();
        const int enterExitOperations = 1;
        double duration = 0;

        if ((selectedEmployeDayinout.Count() % enterExitOperations) == 0)
        {
            for (var i = 0; i < selectedEmployeDayinout.Count(); i++)
            {
                var enterDate = selectedEmployeDayinout[i].DateTime;
                var leaveDate = selectedEmployeDayinout[i + 1].DateTime;
                duration += leaveDate.Subtract(enterDate).TotalMinutes;
            }
            return duration;
        }
        return duration;
    }

但是当我向这个函数发送集合时,这会产生错误:

  

类型&#39; System.ArgumentOutOfRangeException&#39;的例外情况发生在mscorlib.dll但未在用户代码中处理附加信息:索引超出范围。必须是非负数且小于集合的大小。

2 个答案:

答案 0 :(得分:1)

你的问题在于这一行

 for (var i = 0; i < selectedEmployeDayinout.Count(); i++)

您从0循环到selectedEmployeDayinout.Count() 减一。然后在循环内

var leaveDate = selectedEmployeDayinout[i + 1].DateTime;

该错误,因为在上一次迭代中,您在索引selectedEmployeDayinout处访问selectedEmployeDayinout.Count()(在最后一次迭代时该值减去一,然后加一)。

您应该将for (var i = 0; i < selectedEmployeDayinout.Count(); i++)更改为for (var i = 0; i < selectedEmployeDayinout.Count()-1; i++)

答案 1 :(得分:-1)