1
\$\begingroup\$

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++;
    }
}
\$\endgroup\$
  • 2
    \$\begingroup\$ It would be helpful for the review if the source of entire function was in the question. It would be even more helpful if the entire class and the definition of attendance was included in the question. We need more context. \$\endgroup\$ – pacmaninbw Apr 30 at 11:05
  • \$\begingroup\$ @pacmaninbw the class big \$\endgroup\$ – Avinash Reddy Apr 30 at 11:06
1
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ In should have out lets say i have 4 records then no problem 0 is in= true 1 is out=true`` 2 in = true 3 out =true done. in case I got only 3 records then` 0 in =true 1 out =true 2 both in and out is false` \$\endgroup\$ – Avinash Reddy May 1 at 10:03
  • \$\begingroup\$ so this thing don`t set anything for last record always \$\endgroup\$ – Avinash Reddy May 1 at 10:04

Not the answer you're looking for? Browse other questions tagged or ask your own question.