我在列表集合中有一些日期,如下所示
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但未在用户代码中处理附加信息:索引超出范围。必须是非负数且小于集合的大小。
答案 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)
您可以使用TimeSpan类计算c#
中的时差https://msdn.microsoft.com/en-us/library/system.timespan.seconds(v=vs.110).aspx