Setting alternative records true if its even count else leave last record [closed]

Posted on

Problem

I have an attendance list like this.

problem: I need to set In and Out alternatively. but if I have only 3 records then I need to set 0 record In true. 1 record out is true. and 3 record has is both In Out is false. I tried like this its working fine. but I was checking is there any better way

ObservableCollection<EmployeeAttandance> attendancesPerDay = new ObservableCollection<EmployeeAttandance>();
if (attendancesPerDay.Count % 2 == 0)
{
    int counter = 0;
    foreach (var attendance in attendancesPerDay)
    {
        if (counter % 2 == 0)
            attendance.In = true;
        else
            attendance.Out = true;
        counter++;
    }
}
else
{
    int counter = 0;
    foreach (var attendance in attendancesPerDay)
    {
        if (attendancesPerDay.IndexOf(attendance) == attendancesPerDay.Count - 1)
            continue;
        if (counter % 2 == 0)
            attendance.In = true;
        else
            attendance.Out = true;
        counter++;
    }
}

Solution

In the else clause it might be better to have an if statement with a block of code than a continue statement:

    foreach (var attendance in attendancesPerDay)
    {
        if (attendancesPerDay.IndexOf(attendance) != attendancesPerDay.Count - 1)
        {
            if (counter % 2 == 0)
                attendance.In = true;
            else
                attendance.Out = true;
            counter++;
        }
    }

The logic is basically the same and it is easier to see the scope of the code.

To reduce the repetition of the code there could be a short function that takes 2 parameters, counter and attendance and performs the assignment.

As a personal choice I prefer to specify the real type in a foreach loop because it is self documenting, the user of var hides too much.

Leave a Reply

Your email address will not be published. Required fields are marked *