【问题标题】:How to Calculate time in Seconds From multiple Dates? [duplicate]如何从多个日期计算以秒为单位的时间? [复制]
【发布时间】:2017-05-30 22:39:38
【问题描述】:

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

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;
    }

但是当我将集合发送到此函数时,会出现错误:

mscorlib.dll 中出现“System.ArgumentOutOfRangeException”类型的异常,但未在用户代码中处理其他信息:索引超出范围。必须为非负数且小于集合的大小。

【问题讨论】:

  • 错误是什么
  • **循环错误**
  • @SavitaVerma:上面写了什么?
  • 实际上我正在通过循环从集合中计算时间 10:00 - 10:30 = 30 分钟 10:30 - 11:30 = 60 分钟 ** 总计算时间为 90 分钟 **跨度>
  • @SavitaVerma :很好,有什么问题吗?您收到的错误消息是什么?

标签: c# indexoutofboundsexception


【解决方案1】:

你的问题出在这一行

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

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

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

这是错误的,因为在最后一次迭代中,您在索引selectedEmployeDayinout.Count() 处访问selectedEmployeDayinout(该值在最后一次迭代中减一,然后加一)。 p>

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

【讨论】:

    【解决方案2】:

    【讨论】:

    • 他做到了。注意Subtract 调用,它返回一个TimeSpan 实例。
    猜你喜欢
    • 2018-07-30
    • 1970-01-01
    • 1970-01-01
    • 2022-11-27
    • 1970-01-01
    • 2021-05-25
    • 2016-02-14
    • 2020-04-22
    相关资源
    最近更新 更多