views:

56

answers:

1

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.

+1  A: 

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
I kinda like your solution better than mine :P
JoseMarmolejos