0

Let's say you have a Classroom entity with an collection of Student entities. What I usually do when creating a new Student and need to add it to the Classroom is use Classroom.Students.Add(newStudent), now when I want to update this collection I normally clear() the collection and add the students again, something like:

theClassroom.Students.Clear();

foreach(Student student in updatedStudentsCollection) {
    theClassroom.Students.Add(student);
}

Clearing the collection and adding the entities again feels somewhat quirky, so I guess there should be a better strategy for this scenario. Please share how do you normally handle this.

andyp
  • 6,229
  • 3
  • 38
  • 55
JoseMarmolejos
  • 1,760
  • 1
  • 17
  • 34
  • Are you talking about the scenario when you update you student collection from code or from the DB? In other words, where does updatedStudentsCollection come from in your example? – Yakimych Jul 08 '10 at 14:15
  • From code, let's assume there's a CassroomService with an UpdateStudentsForClassroom(students) that takes the updated collection or an UpdateClassrroom(clasroom) that takes an entire classroom object that includes the updated collection. – JoseMarmolejos Jul 08 '10 at 15:54

1 Answers1

1

You could iterate over your database collection of students and remove all students that are not in the updatedStudentsCollection and add all students that are in the updated collection but not in the database collection. But if that's really less quirky.. ;-)

theClassroom.Students.Remove(x => !updatedStudentsCollection.Contains(x));
foreach (var student in updatedStudentsCollection)
    if (!theClassroom.Students.Contains(student))
        theClassroom.Students.Add(student);
andyp
  • 6,229
  • 3
  • 38
  • 55