-1

I have some dates in list collection as given below

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

from sing this function i am calculating time in seconds from a date collection

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

but when i sent collection to this function this gives errors:

An exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll but was not handled in user code Additional information: Index was out of range. Must be non-negative and less than the size of the collection.

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179

2 Answers2

1

Your problem lies on this line

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

You loop from 0 to selectedEmployeDayinout.Count() minus one. And then inside the loop

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

That's error because for the last iteration you access selectedEmployeDayinout at index selectedEmployeDayinout.Count() (that value minus one at last iteration and then plus one).

You should change for (var i = 0; i < selectedEmployeDayinout.Count(); i++) to for (var i = 0; i < selectedEmployeDayinout.Count()-1; i++)

Niyoko
  • 7,512
  • 4
  • 32
  • 59
-1

You can use TimeSpan class to calculate Time difference in c#

https://msdn.microsoft.com/en-us/library/system.timespan.seconds(v=vs.110).aspx

Shakeer Hussain
  • 2,230
  • 7
  • 29
  • 52