Skip to content

Instantly share code, notes, and snippets.

@HamidMolareza
Last active April 16, 2020 12:20
Show Gist options
  • Save HamidMolareza/d115fde80221e48aa460dcc6143792fe to your computer and use it in GitHub Desktop.
Save HamidMolareza/d115fde80221e48aa460dcc6143792fe to your computer and use it in GitHub Desktop.
public void UpdateInstructorCourses(int[] selectedCourses, Instructor instructorToUpdate)
{
if (selectedCourses == null)
{
instructorToUpdate.CourseAssignments = new List<CourseAssignment>();
return;
}
var selectedCoursesHS = new HashSet<int>(selectedCourses);
var instructorCourses = new HashSet<int>
(instructorToUpdate.CourseAssignments.Select(c => c.Course.CourseID));
var targetCoursesId = new HashSet<int>(selectedCourses);
targetCoursesId.UnionWith(instructorCourses);
foreach (var courseId in targetCoursesId)
{
if (selectedCoursesHS.Contains(courseId))
{
if (!instructorCourses.Contains(courseId))
{
instructorToUpdate.CourseAssignments.Add(
new CourseAssignment
{
InstructorID = instructorToUpdate.ID,
CourseID = courseId
});
}
}
else
{
CourseAssignment courseToRemove
= instructorToUpdate
.CourseAssignments
.SingleOrDefault(i => i.CourseID == courseId);
_context.Remove(courseToRemove);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment