I am currently developing a system in which teachers can manage the enrollment of students in their classes. The user interface allows them to add or remove students, as well as update details such as the class name and room number.
Right now, I am implementing a process where students not included in the request are removed from the class, and new students are added accordingly.
public async Task UpdateSectionEnrollment(long sectionId, List<long> students)
{
var sectionSchedule = await _scheduleRepository.GetAll()
.Where(a => a.SectionId == sectionId)
.ToListAsync();
var allEnrolledUserIds = sectionSchedule.Select(a => a.UserId).ToList();
//Add new students
var newEnrollement = students.Except(allEnrolledUserIds);
var removeStudents = allEnrolledUserIds.Except(students);
// add new students to section enrolment
foreach (var userId in newEnrollement)
{
await _scheduleRepository.InsertAsync(new SectionStudent(userId, sectionId));
}
var sections = sectionSchedule.Where(s => removeStudents.Any(id => id == s.Id));
foreach (var section in sections)
{
await _scheduleRepository.DeleteAsync(section);
}
await CurrentUnitOfWork.SaveChangesAsync();
}
Is there a more efficient way to handle this process? Should each student addition or removal be done individually rather than in batches?